我有一个 Post has_many Comments 关联。Post 具有布尔属性published
。当post.published
为假时,新的评论不应该是有效的。完成这种验证的最佳实践是什么?
我试图通过这种方式做到这一点,但遗憾的是,它不能正常工作。仍然可以为未发布的帖子创建新评论。
class Comment < ActiveRecord::Base
validates :post_id, presence: true, if: :post_is_published
...
def post_is_publised
post && post.published
end
end