在 acts_as_commentable gem 中添加验证

Add validation in acts_as_commentable gem

我正在使用一个名为 acts_as_commentable

的 gem

我在迁移中添加了一个自定义列,例如:recipient_id

然后我根据文档生成了一个 Comment 模型:

rails g comment

现在,在我的 Comment.rb 中,我有以下行:

validate :comment, :recipient_id, :presence => true

注意:comment 列已由 gem 自己添加

仍然,在遵循文档之后,当我故意触发以下内容时:

commentable = Post.create(:title => ......)
comment = commentable.comments.create
comment.comment = "Some comment"
comment.recipient_id = nil
comment.save!

评论对象看起来像:

<Comment id: 1, comment: "Some comment", commentable_id: 1, commentable_type: "Post", recipient_id: nil, created_at: "2015-06-13 09:41:23", updated_at: "2015-06-13 09:41:23">

为什么它不验证 recipient_id 的存在?

您正在呼叫 validate 而不是 validates。他们都是不同的。

应该是:

validates :comment, :recipient_id, :presence => true