user1179942
user1179942

Reputation: 391

Custom validation in Rails

I have a Post has_many Comments association. Post has boolean attribute published. When post.published is false, the new comment shouldn't be valid. What is the best practise to accomplish this kind of validation?

I've tried to do it by this way, but sadly, it doesn't work correctly. It is still possible to create new comment for unpublished post.

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

  ...
  def post_is_publised
    post && post.published
  end
end

Upvotes: 0

Views: 84

Answers (1)

Adrian Serafin
Adrian Serafin

Reputation: 7725

Hmm.. I think you have syntax errors in your code... Try this:

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

  def post_is_publised
    post.try(:published)
  end
end

After reading your console output and checking your question one more time:

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

I understand that you don't want to allow adding comments to unpublished posts. Above code should accomplish that.

Upvotes: 1

Related Questions