2013-06-24 2 views
0

코멘트 모델에 대한 사용자 정의 유효성 검증을 수행합니다. 등록되지 않은 사용자는 등록 된 사용자의 전자 메일을 주석 제출시 사용하지 않아야합니다.헬퍼 메소드를 사용한 사용자 정의 유효성 검사

나는 사용자 정의 유효성 검사기 클래스 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 

그리고 내 모델 파일 app/models/comment.rb

:

class Comment < ActiveRecord::Base 
    include ActiveModel::Validations 
    validates_with ValidateCommentEmail 
    ... 
end 

문제는 내가 내 sessions_helper.rb에서 current_user 방법을 사용하는 것이 있습니다 :

def current_user 
    @current_user ||= User.find_by_remember_token(cookies[:remember_token]) 
end 

검사기가 th를 볼 수 없습니다. 방법입니다. Validator 클래스에 sessions_helper를 포함 할 수 있지만 쿠키 방법에 대한 오류가 발생합니다. 그것은 어디에도없는 길입니다. 이 사용자 정의 유효성 검사 레일을 만드는 방법은 무엇입니까? ,

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 

그렇지 않다면 나는이 검증 표준 유효성 검사기를 사용하여 수행 할 수 없습니다한다고 생각 :이 등록 된 사용자 (belongs_to :user)에 의해 생성 된 경우 주석이 알고있는 경우

+0

댓글은 author_email 외에 사용자와 직접 연관 될 수 있습니까? – PinnyM

+0

나는'current_user.nil? '을 호출하여 코멘트하는 사용자가 등록되어 있지 않은지 확인하려고한다. 주석 레코드에 연관된 사용자가 있는지 여부를 확인할 수 있습니까? 그렇게하면'current_user'가 필요 없습니다. – mario

+0

기존 사용자가 주석을 제출하면 사용자와 직접 연관됩니다. 그러나 등록되지 않은 사용자가 등록 된 사용자의 전자 메일을 사용하지 않는지 확인하고 싶습니다. 그래서 나는이 사용자를 확인해야한다. 1. 로그인하지 않았다. 2. 그의 전자 메일은 등록 된 전자 메일의 배열이 아닙니다. –

답변

0

, 당신은 단순히에 대해 확인할 수 있습니다. 모델이이 기준을 충족시키는지를 결정하는 데 충분한 상황을인지하지 못합니다. 대신 컨트롤러 자체에서 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 
+0

좋아요! 감사합니다!) –

+0

@AlexFedoseev : 'exists?'를 사용하여 일치하는 이메일을보다 효율적으로 확인할 수 있습니다 - 업데이트 된 내용을 참고하십시오. – PinnyM

관련 문제