我试图使用的form_for以下字段创建一个使用多种类型。然而,一些字段对应于一个模型中,RecipeIngredient类(模型),而底部场对应于配方类(模型)。中的form_for的Rails
<%= form_for(:recipe_and_ingredients, :url => {:action => 'create'}) do |f| %>
<!-- RecipeIngredient classs -->
<table>
<tr>
<td>4</td>
<td><%= f.text_field(:quantity) %></td>
<td><%= f.text_field(:weight) %></td>
<td><%= f.text_field(:units) %></td>
</tr>
</table>
<!-- Recipe class -->
<table summary="Recipe form fields">
<tr>
<th>Recipe Name</th>
<td><%= f.text_field(:recipe_name) %></td>
<th>Total Grams</th>
<td><%= f.text_field(:total_grams) %></td>
</tr>
</table>
<div class="form-buttons">
<%= submit_tag("Create Recipe") %>
</div>
<% end %>
然而,在我的控制器:
# Instantiate a new object using form parameters
@recipe = Recipe.new(params[:recipe_and_ingredients])
@ingredient = RecipeIngredient.new(params[:recipe_and_ingredients])
我得到这个错误,当我提交表单
unknown attribute: quantity
我知道这是因为配方模型/类/表/什么没有数量栏;这是RecipeIngredient中的一个列(如果这是相关的,它应该是Recipe和其他表之间的连接表)。但是,当我提交参数时,如何在代码中区分哪些参数属于哪个类?
我有'食谱has_many食物'和'食物has_many食谱',并且我使用':through'和一个名为'Recipe_Ingredients'的连接表。我是不是应该'accepts_nested_attributes_for'在配方模型和Recipe_Ingredients加入模型,或只是其中之一? – lordmarinara 2012-02-23 22:24:35
我更新了答案,并说明了它的布置方式。对于你的问题: - 如果您希望能够为“一次”的recipie添加许多成分,那么你需要在'Recipie'了'has_many'的和'RecipieIngredient'第一'belongs_to'。如果你希望能够将一种成分同时添加到一组Recipies中,那么你需要''成分'中的'has_many'和第二个'belongs_to'。 – 2012-02-23 23:07:39
好的,谢谢! – lordmarinara 2012-02-25 19:29:42