I want to make custom validation for Comment model: unregistered users shouldn't use e-mails of registered users, when they submitting comments.
I put custom validator class app/validators/validate_comment_email.rb
:
class ValidateCommentEmail < ActiveModel::Validator
def validate(record)
user_emails = User.pluck(:email)
if current_user.nil? && user_emails.include?(record.comment_author_email)
record.errors[:comment_author_email] << 'This e-mail is used by existing user.'
end
end
end
And in my model file app/models/comment.rb
:
class Comment < ActiveRecord::Base
include ActiveModel::Validations
validates_with ValidateCommentEmail
...
end
The problem is that I use current_user
method from my sessions_helper.rb
:
def current_user
@current_user ||= User.find_by_remember_token(cookies[:remember_token])
end
Validator can't see this method. I can include sessions_helper in Validator class, but it gives me an error about cookies method. It's a road to nowhere. So how to make this custom validation rails way?