我已经实现了简单的表单来注册带有验证码的用户。 一切都工作正常,但我无法管理验证错误以显示在视图上,它看起来很容易,但我想我在这里缺少一些要点。 这是我的模特
class Email < ActiveRecord::Base
apply_simple_captcha :message => "The secret Image and code were different", :add_to_base => true
validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/ , :message => "Invalid Email Format"
end
然后是我的观点
<%= form_for(@email, url: emails_new_path) do |f| %>
<div class="field">
<%= f.text_field :email, placeholder: "Enter Email" %>
</div>
<%= show_simple_captcha(:email=>"email", :label => "Human Authentication", :placeholder => "Enter the code") %>
<div class="actions">
<%= f.submit "Sign up" %>
</div>
<%= @email.errors.full_messages.first if @email.errors.any? %>
<% end %>
控制器
class EmailsController < ApplicationController
def new
@email = Email.new(user_params)
if !user_params.nil?
if simple_captcha_valid?
puts "Right captcha"
@email.save!
if @email.save
flash[:success] = "Thanks! We will be in touch soon!"
redirect_to :action => 'new'
else
flash[:success] = "Invalid Emails"
render :action => 'new'
end
else
puts "Wrong captcha"
flash[:success] = "Wrong Emails"
end
end
end
def user_params
params.require(:email).permit(:email) if params[:email]
end
end
所以问题是我如何管理模型和控制器上的消息,以便在按钮点击时显示在视图上。 感谢
答案 0 :(得分:0)
您可以使用save_with_captcha
进行验证,例如:
@email = Email.new(user_params)
if @email.save_with_captcha
puts "Right captcha"
else
puts "error with captcha"
end