Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
605 views
in Technique[技术] by (71.8m points)

ruby on rails - validates_associated not checking existence of associations

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...