0

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?

4

1 回答 1

0

如果评论知道它是否是由注册用户 ( belongs_to :user) 创建的,您可以简单地检查一下:

def validate(record)
  if record.user_id.nil? && User.where(:email => record.comment_author_email).exists?
    record.errors[:comment_author_email] << 'This e-mail is used by existing user.'
  end
end

如果不是,我认为不应使用标准验证器执行此验证。它不会知道足够的上下文来确定模型是否符合此标准。相反,您应该通过从控制器本身传递 current_user 来手动检查:

# in comments_controller.rb
def create
  @comment = Comment.new(params[:comment])
  if @comment.validate_email(current_user) && @comment.save
   ...
end

# in comment.rb
def validate_email(current_user)
  if current_user.nil? && User.where(:email => record.comment_author_email).exists?
    errors[:comment_author_email] << 'This e-mail is used by existing user.'
  end
end
于 2013-06-24T19:57:20.390 回答