wok*_*ena 2 validation ruby-on-rails
我真的不知道验证用户输入的建议.我正在开始与RoR.我读了很多关于这个问题的网页,但我从来没有得到过,我想要的是什么.在RoR之前,我用Java编程.我的问题是:如何验证空字段并显示错误消息?这是代码片段:
polls_controller.rb
class PollsController < ApplicationController
def create
@poll = Polls.new
@poll.question = params[:question]
@poll.author_ip = request.remote_ip
end
def show
end
def new
end
def edit
end
end
Run Code Online (Sandbox Code Playgroud)
polls.rb
class Polls < ActiveRecord::Base
has_many :options
validates_presence_of :question, :message => 'Something is wrong...'
end
Run Code Online (Sandbox Code Playgroud)
create.html.erb
<p>
<% form_tag polls_path do %>
<%= label_tag :question, "Enter your question:" %><br>
<%=text_field_tag :question, params[:question] %>
<%=submit_tag "Send" %>
<% end %>
</p>
Run Code Online (Sandbox Code Playgroud)
首先,不要向验证添加无意义的消息,默认的错误消息是好的.
其次,在控制器中将代码更改为类似的内容:
def new
@pool = Pool.new
end
def create
@pool = Pool.new(params[:pool])
if @pool.save
flash[:notice] = "Some text indicating it was created"
redirect_to pool_path(@pool)
else
flash[:error] = "Something is wrong while validating"
render :new
end
end
Run Code Online (Sandbox Code Playgroud)
并查看使用表单助手:
<% form_for @pool do |f| %>
<%= f.error_messages %>
<%= f.label :question, "Enter your question:" %><br>
<%= f.text_field :question %><br>
<%= submit_tag "Send" $>
<% end %>
Run Code Online (Sandbox Code Playgroud)
这样您就可以在模式下进行验证,而在控制器中,您只需要检查是否可以保存模型.它不会,然后在您的视图窗体中可以显示该模型的error_messages.
用于在布局位置显示Flash消息:
<% if flash[:notice] -%>
<p class="notice"><%= flash[:notice] %></p>
<% end -%>
<% if flash[:error] -%>
<p class="error"><%= flash[:error] %></p>
<% end -%>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12395 次 |
| 最近记录: |