How To Create Different Submit Actions in Rails 3 with respond_with
我希望能够通过使用respond_with提交的表单执行以下操作:
respond_with 的默认操作是重定向到 show 操作。如何让控制器根据点击的按钮类型做出响应?
这些"提交"将在创建和更新操作期间发生。例如,此代码中的创建操作将如何响应单击三个提交按钮中的任何一个(提交和编辑、提交和显示、提交和显示索引)
1 2 3 4 5 6 7 8 9 | def new respond_with(@business=Business.new) end def create @business = Business.new(params[:business]) flash[:notice] = t("flash.actions.create.notice", {:resource_name =>"Business"}) if @business.save respond_with(@business) end |
在您看来,使用值
1 2 3 4 5 6 7 8 9 10 11 12 13 | def create @business = Business.new(params[:business]) flash[:notice] = t("flash.actions.create.notice", {:resource_name =>"Business"}) if @business.save location = case params[:submit] when 'submit_and_edit' edit_business_url when 'submit_and_show' business_url when 'submit_and_show_index' redirect_to businesses_url end respond_with(@business, :location => location) end |
一般来说,只有一个提交按钮是一种很好的做法,这样用户就可以预期接下来会发生什么(通常是转到显示页面)。
如果你想要3个提交按钮,那么你可以在提交前使用Javascript在数据上设置一个字段。在 HTML(假设 ERB)中添加一个隐藏字段和 id 到按钮:
1 2 3 4 5 | <%= hidden_field_tag :action,"", id='next_action' %> <%= f.submit"Submit and Show, id='show' %> <%= f.submit"Submit and Edit id='edit'%> <%= f.submit"Submit and Index id='index'%> |
现在你需要添加点击处理程序,所以在 .js.coffee:
1 2 3 | $(":submit").click -> $('#next_action').val = $(this).attr('id') $(this).closest(':form').submit() |
那应该找到id为next_action\\'的隐藏字段,将其值设置为点击按钮的id,然后提交表单。
现在在您的控制器中您将可以访问