2011-08-11 2 views
2

이 깨끗한 코드를하지 않을 수도 있습니다시기를 지정 유효성 검사는 여전히 아직 루비 아주 새로운 실패하지 레일 는 ... 그것은

나는 내 message.rb 모델에서 다음과 같은 스팸 검사 방법이 있습니다

validate :no_spam?, :if => "sender_user_id != nil" 

private 

def no_spam? 
    #first easy spam detection, if the (hidden by css) company field is filled, it is spam for sure 
    if !company.blank? 
    errors.add(:body, I18n.t(:No_spam_allowed)) 
    return false 
    end 

    #Mollom advanced spam detection 
    m = Mollom.new(:private_key => 'xxx', 
       :public_key => 'xxx') 

    #check content in case it is a first submit of the form 
    if captcha_session_id.blank? 
    content = m.check_content(:post_body => body, 
           :author_name => sender_name, 
           :author_mail => sender_email, 
           :author_ip => sender_ip) 
    else 
    #check captcha if the form was resumbitted after an unsure result 
    logger.debug "DEBUG: GOING TO CHECK CAPTCHA" 
    result = m.valid_captcha?(:session_id => captcha_session_id, 
           :solution => captcha_solution.chomp) 
    if result 
     logger.debug "DEBUG: TRUE -> GOOD CAPTCHA" 
     return true 
    else 
     logger.debug "DEBUG: FALSE -> BAD CAPTCHA" 
     return false 
    end 
    end 

    #returning the right values and error messages for different content check outcomes 
    logger.debug "DEBUG: I'M CONTINUING THE METHOD EXECUTION" 
    if content.spam? 
    logger.debug "DEBUG: SPAM DETECTED" 
    errors.add(:body, I18n.t(:No_spam_allowed)) 
    return false 
    elsif content.unsure? 
    logger.debug "DEBUG: MESSAGE UNSURE - FAIL FORM BUT SHOW CAPTCHA" 
    errors.add(:captcha_solution, I18n.t(:Type_the_characters_you_see_in_the_picture_below)) 
    self.captcha_image_url = m.image_captcha(:session_id => content.session_id)["url"] 
    self.captcha_session_id = content.session_id 
    return false 
    else 
    logger.debug "DEBUG: MESSAGE OK!" 
    return true 
    end 
end 
에게

이 사이트에 (Mollom에서 불확실한 결과를 호출하기 위해 본문에 '확실'로 처음 양식 (첫 번째 작업을 생성) 제출 것을 볼 수있는 development.log 파일에서 development.log 파일

Processing MessagesController#create (for 127.0.0.1 at 2011-08-12 12:01:24) [POST] 
    Parameters: {"commit"=>"Verzend", "action"=>"create", "authenticity_token"=>"xxxxxxxxxxx", "locale"=>"nl", "controller"=>"messages", "message"=>{"sender_email"=>"[FILTERED]", "company"=>"", "body"=>"unsure", "sender_phone"=>"xxxx", "sender_name"=>"Admin ImmoNatie"}} 
    Message Columns (6.0ms) SHOW FIELDS FROM `messages` 
    User Columns (10.0ms) SHOW FIELDS FROM `users` 
    User Load (7.0ms) SELECT * FROM `users` WHERE (`users`.`id` = '1') AND (users.deleted_at IS NULL) LIMIT 1 
    SQL (0.0ms) BEGIN 
    User Update (0.0ms) UPDATE `users` SET `updated_at` = '2011-08-12 10:01:25', `perishable_token` = 'xxxxxxxxxxx', `last_request_at` = '2011-08-12 10:01:25' WHERE `id` = 1 
    SQL (3.0ms) COMMIT 
    SQL (0.0ms) BEGIN 
DEBUG: I'M CONTINUING THE METHOD EXECUTION 
DEBUG: MESSAGE UNSURE - FAIL FORM BUT SHOW CAPTCHA 
    SQL (0.0ms) ROLLBACK 
Rendering template within layouts/application 
Rendering messages/new 
Rendered messages/_form (8.0ms) 
Rendered layouts/_google_analytics (0.0ms) 
Rendered layouts/_login (3.0ms) 
Rendered layouts/_navigation (6.0ms) 
Rendered layouts/_header (12.0ms) 
Rendered about_us/_ten_reasons_9_body (0.0ms) 
    NewsletterEmail Columns (5.0ms) SHOW FIELDS FROM `newsletter_emails` 
Rendered layouts/_footer (41.0ms) 
Completed in 1907ms (View: 70, DB: 40) | 200 OK [http://infinitize.dynalias.com/contact] 
tize.dynalias.com/contact] 
    SQL (0.0ms) SET SQL_AUTO_IS_NULL=0 
    Property Columns (10.0ms) SHOW FIELDS FROM `properties` 


Processing MessagesController#create (for 127.0.0.1 at 2011-08-12 12:01:32) [POST] 
    Parameters: {"commit"=>"Verzend", "action"=>"create", "authenticity_token"=>"xxxxxxxxxxx", "locale"=>"nl", "controller"=>"messages", "message"=>{"sender_email"=>"[FILTERED]", "company"=>"", "body"=>"unsure", "captcha_solution"=>"", "sender_phone"=>"xx", "captcha_session_id"=>"xxxxxxxxxxx", "sender_name"=>"Admin ImmoNatie"}} 
    Message Columns (5.0ms) SHOW FIELDS FROM `messages` 
    User Columns (10.0ms) SHOW FIELDS FROM `users` 
    User Load (0.0ms) SELECT * FROM `users` WHERE (`users`.`id` = '1') AND (users.deleted_at IS NULL) LIMIT 1 
    SQL (0.0ms) BEGIN 
    User Update (0.0ms) UPDATE `users` SET `updated_at` = '2011-08-12 10:01:32', `perishable_token` = 'xxxxxxxxxxx', `last_request_at` = '2011-08-12 10:01:32' WHERE `id` = 1 
    SQL (4.0ms) COMMIT 
    SQL (0.0ms) BEGIN 
DEBUG: GOING TO CHECK CAPTCHA 
DEBUG: FALSE -> BAD CAPTCHA 
    Message Create (0.0ms) INSERT INTO `messages` (`sender_email`, `receiver_user_id`, `receiver_email`, `created_at`, `body`, `opened_by_owner`, `updated_at`, `receiver_name`, `opened_by_sender`, `sender_ip`, `message_thread_id`, `sender_user_id`, `sender_name`) VALUES('[email protected]', 1, '[email protected]', '2011-08-12 10:01:33', 'unsure', NULL, '2011-08-12 10:01:33', 'ImmoNatie', NULL, '127.0.0.1', NULL, 1, 'Admin ImmoNatie') 
    MessageThread Columns (5.0ms) SHOW FIELDS FROM `message_threads` 
    MessageThread Create (1.0ms) INSERT INTO `message_threads` (`last_message_opened_by_sender_id`, `answered`, `initial_sender_user_id`, `created_at`, `initial_sender_email`, `starred`, `updated_at`, `last_message_opened_by_owner_id`, `type_id`, `owner_id`, `property_id`, `first_message_id`, `initial_sender_name`, `initial_sender_phone`, `last_message_id`, `last_message_added_at`) VALUES(213, NULL, 1, '2011-08-12 10:01:33', '[email protected]', 0, '2011-08-12 10:01:33', 0, 174, 1, NULL, 213, 'Admin ImmoNatie', 'xx', 213, '2011-08-12 10:01:33') 
    Message Update (0.0ms) UPDATE `messages` SET `updated_at` = '2011-08-12 10:01:33', `message_thread_id` = 101, `sender_name` = 'Admin ImmoNatie', `created_at` = '2011-08-12 10:01:33', `sender_email` = '[email protected]', `sender_ip` = '127.0.0.1', `sender_user_id` = 1, `receiver_name` = 'ImmoNatie', `receiver_email` = '[email protected]', `body` = 'unsure', `receiver_user_id` = 1 WHERE `id` = 213 
Sent mail to [email protected] 

Date: Fri, 12 Aug 2011 12:01:33 +0200 
From: Notifications <[email protected]> 
To: [email protected] 
Subject: Nieuw contact bericht 
Mime-Version: 1.0 
Content-Type: text/html; charset=utf-8 

Naam: xxxx<br /> 
E-mail: xxxx<br /> 
Telefoon: xxxx<br /> 
<br /> 
Bericht:<br /> 
unsure 
    SQL (3.0ms) COMMIT 

개발 모드).

예상대로이 첫 번째 만들기 동작에 대한 유효성 검사가 실패합니다.

그러나 이제 빈 captcha 인증 코드로 양식을 다시 제출할 때 유효성 검증 메소드는 false를 리턴하지만 저장은 계속되고 결국 COMMITTED되기 때문에 유효성 검증은 수행하지 않습니다.

왜이 유효성 검사가 실패하지 않고 생성 동작을 중단 (롤백)합니까?

덕분에, 마이클

+0

반환 방법을 종료합니다. 이 코드를 넘어서는 결정은 어떻게하고 있습니까? 나는 디버그 문을 보지 않는다 ... 나의 추측은 연속 실행시 다른 코드 경로로 두 번 실행될 수 있다는 것이다. – DGM

+0

안녕 DGM, 그것이 맞았다. logger.debug 줄을 더 추가하고 로그도 추가했습니다. 로그에서 처음에는 확실하지 않은 메시지 탐지 (첫 번째 생성 작업)를 호출 한 다음 빈 captcha 검증으로 양식을 재검색하여 새로운 실패를 호출합니다. 로그에서 잘못된 captcha가 발견되었다는 것을 알 수 있습니다. 'DEBUG : FALSE -> BAD CAPTCHA'이므로 false를 반환해야합니다. 이 메소드는 실제로 종료되지만 유효성 검증은 실패하지 않습니다. 메일 메시지를 보낸 다음 COMMIT을 보았 기 때문입니다. 그래서 질문이 나오면 검증이 기록 저장을 깨지 않는 이유는 무엇입니까? –

+0

DGM의 의견에 따라 문제를 다시 작성하고 제목을 변경했습니다. –

답변

1

문제를 발견. 검증에 거짓을 돌려주는 것은 충분하지 않았습니다. errors.add (: body, "error message") 오류를 추가해야했습니다. 이 오류와 함께 false가 반환되었습니다.