在以往的rails应用中,表单一般都是一个create提交按钮.现在可以通过分析按钮背后的动作来添加按钮以实现其他功能:
譬如,对于一个表单,既可以点击create创建,也可以点击preview预览
下面是表单的代码:
<p>
<b>Title</b><br />
<%= f.text_field :title %>
</p>
<p>
<b>Content</b><br />
<%= f.text_area :content %>
<%= submit_tag "Create" %>
<%= submit_tag "Preview", :name=>"preview_button" %>
</p>
在submit_tag中,对按钮的名字进行了赋值,作用就是将其区别开来,如果没有赋值,那么默认的submit_tag按钮的名字是commit也就是说,在点击create按钮之后,返回controller的参数列表大致是这样:
Parameters: {"commit"=>"Create", "project"=>{"title"=>"project 1 ", "content"=>" project's content"}, "action"=>"create", "controller"=>"projects"}
如果点击preview,返回的参数列表:
Parameters: {"preview_button"=>"Preview", "project"=>{"title"=>"project", "content"=>"project's content"}, "action"=>"create", "controller"=>"projects"}
在controller里可以对返回的参数中的preview_button是否有值来判断是否点击了这个按钮.
所以在controller中,create方法是这样的:
def create
@project = Project.new(params[:project])
respond_to do |format|
if params[:preview_button] || [email protected]
format.html { render :action => "new" }
format.xml { render :xml => @project.errors.to_xml }
else
flash[:notice] = 'Project was successfully created.'
format.html { redirect_to project_url(@project) }
format.xml { head :created, :location => project_url(@project) }
end
end
end
如果params[:preview_button]非空,那么在new模板中将preview的内容显示出来:
<h1>New project</h1>
<div id="preview">
<hr>
<% if params[:preview_button] %>
<h2><%= @project.title %></h2>
<%= textilize @project.content %>
<% end -%>
</div>
<%= error_messages_for :project %>
<% form_for(:project, :url => projects_path) do |f| %>
<%= render :partial => "form", :locals=>{:f=>f} %>
<% end %>
<%= link_to 'Back', projects_path %>
本文转自 fsjoy1983 51CTO博客,原文链接:http://blog.51cto.com/fsjoy/114517,如需转载请自行联系原作者