您可以使用部分添加配料(從配料表中取配料並將其存儲在您的recipes_ingredients表中)。
在你的食譜窗體中添加一個局部呈現
<%= f.fields_for :recipesingredients do |ff| %>
<ol>
<table id = "tabla">
<tr>
<td style = "padding-left: 8px"><%= render 'recipesingredients_fields', :f => ff %></td>
</tr>
</table>
</ol>
<% end %>
<div id = "ingredientsadd"></div>
<%= link_to_add_association 'Add', f, :recipesingredients, 'data-association-insertion-node' => "#ingredientsadd", 'data-association-insertion-method' => "append" %>
然後,內部的部分,你可以添加你想添加到您的recipes_ingredients表中的字段。在這種情況下,我假設你只需要ingredient_id。在這種情況下,您可以使用options_from_collection標記來填充當前存儲在配料表中的值。
<%= f.select :ingredient_id , options_from_collection_for_select(@ingredients, :id, :name)%>
請記住,您的recipes_ingredients需要有recipe_id和ingredient_id字段。另外,配料必須屬於食譜,食譜必須有多種成分。
希望這會有所幫助!
對不起,花了這麼長時間纔回到你身邊。這非常有幫助!只有幾件事情要澄清...由於某種原因,行 <%= f.select:ingredient_id,options_from_collection_for_select(@ingredients,:id,:name)%> 正在引發錯誤,「未定義的方法'map'爲零:NilClass「....任何想法是什麼? –
這意味着你正試圖「映射」的「集合」是空的。你在配料表中有什麼價值嗎? @ingredients(在我的示例中)應該將所有值存儲在Ingredient模型中(@ingredients = Ingredient.all)。 –
我確實在桌子上有配料,但是我最終改變了我將如何爲我的應用做配料 –