Rails:在一个表单中多次提交按钮 [英] Rails: Multi-submit buttons in one Form

查看:130
本文介绍了Rails:在一个表单中多次提交按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个文章模型,并且在文章'新'视图中,我有两个按钮,发布和保存草稿。

我的问题是我怎么知道哪个按钮在控制器中被点击。



我已经有了一个解决方案,但我认为必须有更好的方法。
我目前在该视图中使用的是:

 < div class =actions> 
<%= f.submit发布%>
<%= f.submit保存草稿,:name => 提交%>
< / div>

所以在控制器中,我可以使用 params [:commit] 字符串来处理该动作。

  def create 
@article = Article.new(params [:article])
if params [ :commit] ==Publish
@ article.status ='publish'
//详细信息省略
结束

@ article.save
结束

但我认为使用视图相关的字符串并不好。你能告诉我另一种方法来完成这个吗?



更新:由于这些按钮的形式相同, '创造'行动,这对我来说没问题。我想要的是在创建操作中处理这些内容,例如为Article模型设置一个状态列并保留公开或草稿。 方案

这已在 Railscast第38集中介绍。使用 params 散列来检测哪个按钮被点击是正确的方法:

查看:

 <%= submit_tag'创建'%> 
<%= submit_tag'创建并添加另一个',名称:'create_and_add'%>

控制器:

  if params [:create_and_add] 
#例如,重定向到新表单。

else
#例如,重定向显示新创建的记录。
end


Say I have an Article model, and in the article 'new' view I have two buttons, "Publish" and "Save Draft".

My question is how can I know which button is clicked in the controller.

I already have a solution but I think there must be a better way. What I currently used in the view is:

<div class="actions">
  <%= f.submit "Publish" %>
  <%= f.submit "Save Draft", :name => "commit" %>
</div>

So in the controller, I can use the params[:commit] string to handle that action.

def create
  @article = Article.new(params[:article])
  if params[:commit] == "Publish"
    @article.status = 'publish'
    // detail omitted
  end

  @article.save
end

But I think using the view related string is not good. Could you tell me another way to accomplish this?

UPDATE: Since these buttons are in the same form, they're all going to the 'create' action, and that's OK for me. What I want is to handle that within the create action, such as give the Article model a 'status' column and holds 'public' or 'draft'.

解决方案

This was covered in Railscast episode 38. Using the params hash to detect which button was clicked is the correct approach:

View:

<%= submit_tag 'Create' %>
<%= submit_tag 'Create and Add Another', name: 'create_and_add' %>

Controller:

if params[:create_and_add]
  # Redirect to new form, for example.

else
  # Redirect to show the newly created record, for example.
end

这篇关于Rails:在一个表单中多次提交按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆