Search code examples
ruby-on-railsrubyacts-as-commentable

Add validation in acts_as_commentable gem


I'm using a gem called acts_as_commentable

I have added a custom column in the migration like: recipient_id

Then I generated a Comment model as per documentation:

rails g comment

Now, in my Comment.rb, I have following line:

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

Note: comment column is already added by gem itself

Still, after following documentation, when I fire the following deliberately:

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

The comment object seems like:

<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">

Why it's not validating presence of recipient_id?


Solution

  • Your are calling validate instead of validates. They both are different.

    It should be:

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