2013-07-30 34 views
1

瀏覽:_form.html.erb另存爲編輯行動新紀錄

<%= form_for(@product) do |f| %> 
    <div class="field"> 
    <%= f.label :name %><br /> 
    <%= f.text_field :name %> 
    </div> 
    <div class="field"> 
    <%= f.label :price %><br /> 
    <%= f.number_field :price %> 
    </div> 
    <div class="actions"> 
    <%= f.submit "Save" %> 
    <% if params[:action] == "edit" %> 
     <% f.submit "Save As New" %> 
    <% end %> 
    </div> 
<% end %> 

edit.html.erb

<%= render 'form' %> 

在我的產品控制器我都新,創建,編輯&更新通常定義的操作。

問:這種形式的更新工作正常,但我有一個名爲「另存爲新」新的提交按鈕是它無論如何可以調用編輯產品頁面內創建操作,當一個用戶點擊。

我知道使用條件並檢查params [:commit] ==「Save As New」並嘗試調用另一個動作的可能性,但我不確定是否可以這樣做。我應該如何更新我的控制器才能使其工作。

謝謝了。

回答

3

你可以改變這樣的更新操作:

if params[:commit]=="Save As New" 
    @product = Product.create(params[:product]) 
else 
    @product.update_attributes(params[:product]) 
end 
redirect_to @product 

所以你不會需要一個新的動作,並能處理它沒有添加路線...

+1

是的,他的方式是更好的:) – dax

2

如果我對它有正確的理解,您希望用戶能夠在編輯頁面內部創建新記錄,對嗎?

如果是這樣的話,我想你可以這樣做:

<div class="actions"> 
    <%= f.submit "Save" %> 
    <% if params[:action] == "edit" %> 
     <%= link_to "Save As New", {controller: 'products', 
        action: 'new' 
        }, 
        class: "if there's a css class"} %> 

    <% end %> 
</div>