2010-09-15 81 views
0

我一直在關注構建簡單配方應用程序的rails邊緣指南,現在我正在嘗試分支並做一些更有趣的事情來嘗試瞭解更多關於rails的內容。在其自己的控制器中重用嵌入式表格

我不認爲只能夠在一個嵌入式表單中編輯一個成分,我認爲它可能是一個整潔的食譜/:recipe_id/ingredient /:ingredient_id /編輯頁面,並更新那裏的成分。

但是,我用於編輯配料的表單部分嵌套在配方表單中。 所以它開始與

 
<%= form_for([@recipe, @recipe.ingredients.build]) do |f| % > 

編輯頁面知道祕方是什麼,但它真正想要的是成分。但是,如果我將@recipe更改爲@ingredient,則此配方控制器中的該表單不起作用。

我很確定我不應該用相同的字段做兩個單獨的形式來做到這一點。

--------什麼部分和路由表單的外觀-------- 完整的嵌入形式配方&成分更多的數據是

 
< form_for([@recipe, @recipe.ingredients.build]) do |f| %> 
    <%= f.label :ingredient %> 
    <%= f.text_field :ingredient %> 

    <%=f.label :amount %> 
    <%=f.text_field :amount %> 
<% end %> 

這是從食譜名爲/ show.html.erb

 
<%= render @recipe.ingredients %> 

什麼我現在要做的是能夠調用從成分相同的形式/ edit.html.erb

 
<%= render @ingredients %> 

由於配料中沒有配料控制器中配方的上下文。

有沒有更好的方法來連接配料食譜?我只是意識到,這不是一個真正的嵌套形式,只是從配方頁面中調用它。

回答

2

你有

/recipe/:recipe_id/ingredient/:ingredient_id/edit 

這是編輯現有成分的路線。但你的表格

<%= form_for([@recipe, @recipe.ingredients.build]) do |f| % > 

期待你建立一個屬於@recipe的新成分。

如果你想編輯一個現有的成分,那麼你需要使用你的參數來獲取它。

@recipe = Recipe.find params[:recipe_id] 
@ingredient = @recipe.ingredients.find params[:ingredient_id] 
<%= form_for([@recipe, @ingredient]) do |f| % >  

我真的不知道你在什麼如下例子,但我猜的成分是一種多對多的配方和(比如說)食品之間的連接?如果是這樣的話,與成分屬於配方,而不是許多食譜,那麼你可以這樣做:

/ingredient/:ingredient_id/edit 
@ingredient = Ingredient.find params[:ingredient_id] 
@recipe = @ingredient.recipe 

,因此:

<%= form_for(@ingredient) do |f| % >  

進一步建議:

我不能肯定沒有看到你所有的模板,但你是否在做類似的事情:

<%- form_for @item do |f| -%> 
    <%= f.fields_for :field -%> 

<%- form_for @different_item do |ff| -%> 
    <%= ff.fields_for :another_field -%> 
<%- end -%> 

<%- end -%> 

其實,ca ñ你張貼你的形式的要點如上。

+0

感謝馬克,我認爲我得到的問題是,如果我使用form_for(@ingredient)它打破了嵌套的食譜形式,如果我使用form_for([@ recipe,@ recipe.ingredients.build])它打破了非嵌套的形式。這些表單實際上是相同的,所以我想我不應該重新創建form_for,或者我應該從部分中刪除form_for,並且只需要部分中的其餘表單? – pedalpete 2010-09-16 17:12:15

+0

快速建議添加回答。 – mark 2010-09-16 17:38:15

+0

我添加了我的表單,也許是問題的模板。它看起來不像你發佈的更新。 – pedalpete 2010-09-16 22:26:26