2012-02-21 81 views
0

我试图使用的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和其他表之间的连接表)。但是,当我提交参数时,如何在代码中区分哪些参数属于哪个类?

回答

1

使用 在模型:accepts_nested_attributes_for
在控制器:没有
在路线:没什么
在视图中,在您想要的“嵌套”字段,使用f.fields_for :other_model do |inner|,然后你可以使用点inner.inner_field_name。如果这是RecipieIngredient的内容,并且您将其重命名为配料,我认为内在会成为您的案例的成分。如果ReceieIngredient实际上是根据需要更复杂的连接表重做。

多见于http://railscasts.com/episodes/196-nested-model-form-part-1

我会命名实体的recipies“和“成分”,然后对有fields_for :ingredients do |i|一个recipie形式。

如果你想Ingredient has_many recipiesRecipie has_many ingredients,你可以做到这一点与has_many_through中都指向属于to_both recipie和成分的加入模型IngredientRecipie的车型,但这并不影响形式。这些关系用于检索数据。

请注意,如果你有这些的has_many通过您可以使用simple_form只保持与复选框的关系并没有其他代码的关系来写不是保存一个保存数据等。

更新:

Recipie (model) 
Recipie has_many :recipie_ingredients 
Recipie has many :ingredients, :through => :recipie_ingredients 

Ingredient (model) 
Recipie has_many :recipie_ingredients 
Recipie has many :ingredients, :through => :recipie_ingredients 

RecipieIngredient (model) 
belongs_to :recipies 
belongs_to :ingredients 
+0

我有'食谱has_many食物'和'食物has_many食谱',并且我使用':through'和一个名为'Recipe_Ingredients'的连接表。我是不是应该'accepts_nested_attributes_for'在配方模型和Recipe_Ingredients加入模型,或只是其中之一? – lordmarinara 2012-02-23 22:24:35

+0

我更新了答案,并说明了它的布置方式。对于你的问题: - 如果您希望能够为“一次”的recipie添加许多成分,那么你需要在'Recipie'了'has_many'的和'RecipieIngredient'第一'belongs_to'。如果你希望能够将一种成分同时添加到一组Recipies中,那么你需要''成分'中的'has_many'和第二个'belongs_to'。 – 2012-02-23 23:07:39

+0

好的,谢谢! – lordmarinara 2012-02-25 19:29:42

1

有你能解决这个问题有两种方式。

首先是使用ActiveRecord代表团把孩子模型的属性在父模型。您可以在此处看到如何执行此操作的文档:http://api.rubyonrails.org/classes/Module.html#method-i-delegate

其次,您可以使用嵌套窗体使该窗体的一部分属于不同的模型对象。你可以看到这里的文档:http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html

+0

+1。尽管这是一个相互矛盾的答案,但使用代表是一种很好的做法。 – 2012-02-23 23:13:07