Can anyone figure out what's going on here? I was able to get my code to work the way I want it to, but I can't figure out why validates_associated isn't working as I expect. Here's a snippet of my code:
class Flag < ActiveRecord::Base
belongs_to :user
belongs_to :post
# allow only one flag per post per user
validates_uniqueness_of :user_id, :scope => :post_id
validates :user_id, :post_id, :presence => true
validates_associated :user, :post
attr_accessible :user_id, :post_id
end
With this code I can't save a flag with user_id == nil. I can save a flag with user_id == 12345 (i.e. some user_id not in the database). This is what the validates_associated API specification says:
validates_associated(*attr_names)
Validates whether the associated object or objects are all valid themselves. Works with any kind of association.
...
NOTE: This validation will not fail if the association hasn’t been assigned. If you want to ensure that the association is both present and guaranteed to be valid, you also need to use validates_presence_of.
I was able to get the desired behavior by using this, instead:
validates :user, :post, :presence => true
My understanding of the API specification is that validates_associated checks the associated table to see if a row exists with an id matching the foreign key of Flag provided the foreign key is non-nil. Can anyone offer any insight on this? Am I misunderstanding how validates_associated is supposed to work?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…