2012-04-26 35 views
4

我的形式:如何将自定义函数分配给formtastic动作?

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 

在campaign_controller.rb

<%= 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 %> 

功能和唯一我不明白的是在调用函数时写什么。

回答

2

我不知道究竟你正在尝试与save_and_new动作做,但是我可以告诉你,为什么你不触发它。

默认情况下,要创建一个使用formtastic使用semantic_form_for将使用创下了新纪录create行动,并为现有的记录update行动的REST的约定的形式。如果你成功地击中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 

再次,我不是你想什么用save_and_new动作来完成的,并质疑这种假设可以设置你失望的路径清晰一个更好的设计,但要回答你的直接问题:检查params[:commit]的值在createupdate应该让你在正确的轨道上。

+0

谢谢,凯德,它的工作原理是必须的。解决了。 – 2012-04-27 08:11:37

相关问题