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 on开发者_JAVA百科ly 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?
validates_associated
simply runs the validations that are specified within the associated object's class, it does nothing in regard to foreign keys.
validates :user_id, :presence=>true
ensures the presence of a user_id
in your flag record, but that's all.
validates :user, :presence=>true
is used on the association itself and ensures that foreign keys are properly set up.
Man... all I got was that validates_presence_of
is needed for this to work as you got from the API. Seem's overkill to be checking for association validness, but I'm a noob.
精彩评论