0

我有一个 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
4

1 回答 1

1

嗯..我认为您的代码中有语法错误...试试这个:

class Comment < ActiveRecord::Base
  validates :post_id, :presence => true, :if => :post_is_published

  def post_is_publised
    post.try(:published)
  end
end

在阅读您的控制台输出并再次检查您的问题后:

class Comment < ActiveRecord::Base
  validate :post_has_to_be_published

  def post_has_to_be_published
    unless post.try(:published)
      self.errors.add(:base, "you can add comments only to published posts")
    end
  end
end

我了解您不希望允许向未发布的帖子添加评论。上面的代码应该可以做到这一点。

于 2012-05-04T06:40:26.967 回答