我的表格:
<%= 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 %>
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
routes.rb中:
resources :campaigns do
member do
post 'save_and_new'
end
end
路线,根据功能:
save_and_new_campaign POST /campaigns/:id/save_and_new(.:format) campaigns#save_and_new
而我唯一不理解的是,在行动中要写这个函数.
最佳答案 我不确定你正在尝试用save_and_new动作做什么,但我可以告诉你为什么你没有触发它.
默认情况下,使用semantic_form_for创建formtastic的表单将使用RESTful约定,即为新记录执行create操作,为现有记录执行更新操作.如果您使用第一个提交按钮(标记为“保存”)成功点击了创建/更新操作,但是您希望第二个“保存和新建”按钮执行不同的操作,则需要检查参数的值[ :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
同样,我不清楚你要用save_and_new动作完成什么,并质疑这个假设可能会让你走上更好的设计之路,但回答你的直接问题:检查params [:commit]的值在创建或更新中应该让你在正确的轨道上.