2011-08-11 89 views
6

我目前有幾個表單,我試圖改變提交它的基礎的按鈕,如果我在編輯或新的行動。我創建了兩種形式,但這種味道很糟糕,現在我只使用一種形式的部分。Rails 3 - 基於Action的Forms,Custom Submit Button?

在我的部分結束時,我有這樣的事情在我的形式結束:

<p> 
    <% if controller.action_name == 'new' %> 
    <%= f.submit "Create", :class => "pink_button"%> or 
    <% elsif controller.action_name == 'edit' %> 
    <%= f.submit "Update", :class => "pink_button"%> or 
    <% end %> 
    <%= link_to "cancel", :back %> 
    </p> 

這樣的話,如果我創造了一些新的按鈕顯示爲「創建」,如果這是用戶試圖完成的更新,按鈕顯示「更新」。這很好,直到表單提交併且驗證失敗。

在我的控制,我趕上的事情做不成,像這樣:

def update 
    @list = current_user.lists.find(params[:id])  

    if @list.update_attributes(params[:list]) 
     redirect_to list_path(@list), :notice => "List '#{@list.name}' updated." 
    else 
     render :action => 'edit' 
    end 
    end 

所以,形式簡單地重新呈現。問題是,我不再處於編輯路徑。這意味着,我的表單按鈕不再顯示。

有什麼我想要做的約定?

謝謝

回答

14

是的,這是默認情況下在Rails中用i18n處理的。翻譯是的ActionView,並期待這樣的:

en: 
    helpers: 
    select: 
     # Default value for :prompt => true in FormOptionsHelper 
     prompt: "Please select" 

    # Default translation keys for submit FormHelper 
    submit: 
     create: 'Create %{model}' 
     update: 'Update %{model}' 
     submit: 'Save %{model}' 

所有你需要做的是f.submit(沒有通過「創建」或「編輯」等),翻譯將完成剩下的。您可以通過將上述yaml放入本地語言環境來覆蓋這些。

如果你需要設置類,你可以通過零,例如f.submit nil, :class => 'whatev'

13

Rails的方式是,以檢查是否該記錄是新的或不:

@list.new_record? ? "Create" : "Update" 
+2

薩米爾謝謝!我用這樣的建議:<%= f.submit @ chore.new_record? ? 「發佈你的雜項」:「更新你的雜項」,:class =>「marginTopBottom」%> –

0

Rails有一個方法persisted?以確定對象是否持續存在。

如果您正在使用ERB,做

<%= f.submit (@list.persisted? ? 'Create' : 'Update) %> 

如果您使用HAML,使用

= f.submit (@list.persisted? ? 'Create' : 'Update') 

如需更多信息,請參閱http://apidock.com/rails/ActiveRecord/Persistence/persisted%3F