2012-04-26 32 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

相關問題