开发者

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 defa开发者_如何学运维ult.

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???


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!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜