ruby-on-railsvalidationmodel

validating a belongs_to association


I'm trying to validate a model Student like this;

class Student < ActiveRecord::Base
  belongs_to :room
end

I want to ensure that Room is a valid model, and with that I can only save a student only if the room is valid.

I tried to change the association to:

belongs_to :room, :validate => true

But it didnt change the behaviour.. API says:

:validate
  If false, don’t validate the associated objects when saving the parent object. false by default.

So I changed the validation to room:

class Room < ActiveRecord::Base
  has_many :students, :validate => true
end

but neither options solve for me

any ideas???


Solution

  • Give this a try...

    class Student < ActiveRecord::Base
      belongs_to :room
      validates_associated :room
    end
    

    I'm looking at this portion of the API docs: http://api.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html#method-i-validates_associated

    Also, be careful not to use that validation on both sides of the association!