处理验证错误消息以查看 rails 4
Posted
技术标签:
【中文标题】处理验证错误消息以查看 rails 4【英文标题】:Handle validation error messages to view rails 4 【发布时间】:2015-04-09 08:25:55 【问题描述】:我已经实现了简单的表单来注册带有验证码的用户。 一切正常,但我无法管理要在视图上显示的验证错误,它看起来很容易,但我想我在这里遗漏了一些要点。 这是我的模型
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
所以问题是如何管理来自模型和控制器的消息,以便在按钮单击时显示在视图中。 谢谢
【问题讨论】:
【参考方案1】:您可以使用save_with_captcha
进行验证,例如:
@email = Email.new(user_params)
if @email.save_with_captcha
puts "Right captcha"
else
puts "error with captcha"
end
【讨论】:
以上是关于处理验证错误消息以查看 rails 4的主要内容,如果未能解决你的问题,请参考以下文章