Given
class Post
has_many :comments
end
class Comment
belongs_to :post
end
If I want to validate that a comment always has a post, should I use
class Comment
belongs_to :post
validates :post, presence: true
end
or
class Comment
belongs_to :post
validates :post_id, presence: true
end
?
The Rails guides suggests the validates :post, presence: true
approach, saying:
If you want to be sure that an association is present, you'll need to test whether the associated object itself is present, and not the foreign key used to map the association.
One difference I can see between the two is that if you do
post = Post.new
comment = Comment.new
comment.post = post
comment.save
then validation fails if it's based on post_id
, but succeeds if it's based on post
. The latter makes more sense to me.
However, I sometimes see people in real life using the post_id
approach. Are they simply using the "wrong" approach, or is there a rationale I'm not aware of?
The Rails Style Guide doesn't have anything related to this topic.
The question Rails ActiveRecord:: Proper way for validating presence on associations? seems to be asking about how to get a project to work using the post_id
approach, but doesn't seem to explain why it's using that approach.
Rails 4: Difference between validates presence on id or association is about validation, but merely describes the different effects of the two approaches, rather than saying why post_id
should be used.
The question Rails - Validate Presence Of Association? is unrelated - it's talking about validating that a post has at least one comment, which is a different requirement to what I'm asking about.