On Mon, Feb 7, 2011 at 2:28 PM, Rainer Frey <frey.rai...@gmail.com> wrote:
> But this thread seems to suggest one should simply validate the > association attribute instead. Is that not sufficient then? You can't still be sure the association is valid, because the associated object is cached if previously fetched, and the FK can be changed directly: fxn@halmos:~/tmp/test_belongs_to ∵ cat app/models/post.rb class Post < ActiveRecord::Base has_many :comments end fxn@halmos:~/tmp/test_belongs_to ∵ cat app/models/comment.rb class Comment < ActiveRecord::Base belongs_to :post validates :post, :presence => true end fxn@halmos:~/tmp/test_belongs_to ∵ cat bypass_validation.rb post = Post.create comment = post.comments.create comment.post_id = -1 p comment.save comment.reload p comment.post_id fxn@halmos:~/tmp/test_belongs_to ∵ rails runner bypass_validation.rb true -1 You're going to store the post_id in the database anyway. So if you're going to take the risk of having dangling records, in my view it's better to take the risk on the post_id rather than on the association. I believe that's what the quote from the guide tries to say. The validates_existence plugin performs a query. That's closer to checking the association holds an existing record, but there's still subject to race conditions (say, a concurrent request deleting the associated record outside your transaction). The only way to be totally sure the association does exist is to move the check to who has the key to guarantee that, which is the database with FK constraints. -- You received this message because you are subscribed to the Google Groups "Ruby on Rails: Core" group. To post to this group, send email to rubyonrails-core@googlegroups.com. To unsubscribe from this group, send email to rubyonrails-core+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/rubyonrails-core?hl=en.