Rails:一种形式的多提交按钮 [英] Rails: Multi-submit buttons in one Form

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

问题描述

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

我的问题是如何知道在控制器中点击了哪个按钮.

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

<%= f.submit "Publish" %><%= f.submit "保存草稿", :name =>提交"%>

因此在控制器中,我可以使用 params[:commit] 字符串来处理该操作.

def 创建@article = Article.new(params[:article])if params[:commit] == "发布"@article.status = '发布'//细节省略结尾@article.save结尾

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

UPDATE:由于这些按钮的形式相同,它们都将执行创建"操作,这对我来说没问题.我想要的是在创建操作中处理它,例如给文章模型一个状态"列并保存公开"或草稿".

解决方案

这在 Railscast episode 中有介绍38.使用 params 哈希来检测哪个按钮被点击是正确的方法:

查看:

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

控制器:

if params[:create_and_add]# 例如重定向到新表单.别的# 重定向以显示新创建的记录,例如.结尾

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天全站免登陆