0

I try to make a custom validation for a comment method which will verify that if a comment id is present then it must exists.

class Comment < ActiveRecord::Base
  belongs_to :article
  #Many to one relation with itself (1 comment can have one parent and multiple child)
  has_many :child, class_name: "Comment", foreign_key: "parent_id"
  belongs_to :parent, class_name: "Comment", optional: true

  belongs_to :user, optional: true

  validates :comment, presence: true, length: { minimum: 10 }
  validates :first_name, presence: true, length: { minimum: 2, maximum: 30 }
  validates :last_name, length: { minimum: 2, maximum: 30 }
  validates :comment_id_presence

  private

  def comment_id_presence
    if comment_id != nil && !Comment.exists?(comment_id)
      errors.add(:comment_id, "Le parent doit exister ou être nulle")
    end
  end
end

However, I get the following error : ArgumentError (You need to supply at least one validation). I'd like to know what is my mistake or if there is simplier way to do what I want.

Léo Coletta
  • 1,099
  • 2
  • 12
  • 24
  • See how your (broken) comment_id validation differs from your (working) first_name validation? – Brad Werth Jan 31 '18 at 21:06
  • @BradWerth Yes I fixed it by replacing validate**s** by validate and replacing the comment_id with **:**comment_id. It works but I'm beginner so is it ok ? – Léo Coletta Jan 31 '18 at 21:17
  • yeah... it's a little inconsistant, but obviously ok. do you even need it, with `validates :comment, presence: true, length: { minimum: 10 }`? https://stackoverflow.com/questions/5689888/rails-validate-presence-of-association – Brad Werth Jan 31 '18 at 21:19
  • @BradWerth That's the thing : my :parent_id can be nil but if it is not nil it musth exist in the database. Am I overthinking it ^^ ? – Léo Coletta Jan 31 '18 at 21:26
  • `validates :comment_id_presence` should be `validate :comment_id`. That's what the error is pointing to. – jvnill Jan 31 '18 at 23:30

1 Answers1

2

You should use just validate without s on the end for this case:

validate :comment_id_presence

More here

user3309314
  • 2,453
  • 2
  • 17
  • 30