I’m trying to create a form_for using the following fields. However, some of the fields correspond to one model, the RecipeIngredient class (model), whereas the bottom fields correspond to the Recipe class (model).
<%= 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 %>
However, in my controller:
# Instantiate a new object using form parameters
@recipe = Recipe.new(params[:recipe_and_ingredients])
@ingredient = RecipeIngredient.new(params[:recipe_and_ingredients])
I get this error when I submit the form
unknown attribute: quantity
I know this is because the Recipe model/class/table/whatever does not have a quantity column; that is a column within RecipeIngredient (which is supposed to be a join table between Recipe and some other table if that is relevant). When I submit the params however, how do I differentiate, in the code, which parameters belong to which class?
use
In the model:
accepts_nested_attributes_forIn the controller: Nothing
In the routes: Nothing
In the view, at the point where you want the ‘nested’ fields, use
f.fields_for :other_model do |inner|and then you can useinner.inner_field_name. I think inner would be ingredient in your case, if that is what RecipieIngredient is and you renamed it to ingredient. If receipieIngredient is actually a more complex join table redo as needed.See more at http://railscasts.com/episodes/196-nested-model-form-part-1
I would name the entities ‘recipies’ and ‘ingredients’ and then have a form for a recipie that has
fields_for :ingredients do |i|.If you want
Ingredient has_many recipiesandRecipie has_many ingredients, you can do that too withhas_many_throughin both of the models pointing to a join modelIngredientRecipiewhich belongs to_both recipie and ingredient but that doesn’t affect the form. Those relationships are used to retrieve data.Note that if you have these has_many through you can use simple_form to just maintain the relationship with checkboxes for the relationships and no other code to write other than saving the data with one save.
Update: