我的表格:
<%= semantic_form_for(@campaign) do |f| %>
...
<%= f.actions do %>
<%= f.action :submit, label: "Save"%>
<%= f.action :submit, label: "Save & New" %>
<%= f.action :cancel, label: "Cancel"%>
<% end %>
<% end %>
Run Code Online (Sandbox Code Playgroud)
Campaign_controller.rb 中的函数:
def save_and_new
print 'SAVE_AND_NEW'
@campaign = Campaign.find(params[:id])
respond_to do |format|
if @campaign.update_attributes(params[:campaign])
format.html { redirect_to new_campaign_path, notice: 'Campaign was successfully usaved.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @campaign.errors, status: :unprocessable_entity }
end
end
end
Run Code Online (Sandbox Code Playgroud)
路线.rb:
resources :campaigns do
member do
post 'save_and_new'
end
end
Run Code Online (Sandbox Code Playgroud)
路由,根据功能:
save_and_new_campaign POST /campaigns/:id/save_and_new(.:format) campaigns#save_and_new
Run Code Online (Sandbox Code Playgroud)
我唯一不明白的是,在调用函数时要写什么。
我不确定你到底想用这个save_and_new动作做什么,但我可以告诉你为什么你没有触发它。
默认情况下,您使用 formattastic 创建的表单semantic_form_for将使用 RESTful 约定,即点击create新记录的操作和update现有记录的操作。如果您使用第一个提交按钮(标记为“保存”)成功点击create/update操作,但您希望第二个“保存并新建”按钮执行不同的操作,则需要检查params[:commit]控制器中的值以进行分叉您对提交内容的处理。也许有些代码会更清晰。假设您正在提交更新现有记录:
def create
if params[:commit] == "Save"
# code for handling "Save" scenario
else
# code for handling "Save & New" scenario, perhaps even directly call:
save_and_new
end
end
def update
if params[:commit] == "Save"
# code for handling "Save" scenario
else
# code for handling "Save & New" scenario, perhaps even directly call:
save_and_new
end
end
Run Code Online (Sandbox Code Playgroud)
再说一次,我不清楚你想通过这个save_and_new动作来完成什么,并且质疑这个假设可能会让你走上更好的设计之路,但要回答你直接的问题:检查params[:commit]in的值create或update应该让你开始正确的轨道。