I struggle with nested forms. There're three classes Recipe, Quantity and Ingredient:
class Recipe < ActiveRecord::Base
belongs_to :user
has_many :quantities
has_many :ingredients, through: :quantities
accepts_nested_attributes_for :quantities
class Quantity < ActiveRecord::Base
belongs_to :recipe
belongs_to :ingredient
accepts_nested_attributes_for :ingredient, :reject_if => :all_blank
class Ingredient < ActiveRecord::Base
has_many :quantities
has_many :recipes, :through => :quantities
Recipe Controller
def new
@recipe = current_user.recipes.build
@quantity = @recipe.quantities.build
end
def create
@recipe = current_user.recipes.build(recipe_params)
if @recipe.save
redirect_to @recipe
else
render 'new'
end
end
private
def recipe_params
params.require(:recipe).permit(
:name,
quantities_attributes: [:id, :amount, :ingredient_id],
)
end
View for recipe#new
<%= form_for @recipe, html: {class: "form-horizontal"} do |f| %>
<li class="control-group">
<%= f.label :name, "Recipe Name", class: "control-label" %>
<div class="controls"><%= f.text_field :name %></div>
</li>
<%= f.fields_for :quantities do |quantity| %>
<%= render 'quantity_fields', f: quantity %>
<% end %>
<%= f.submit %>
<% end %>
_quantity_fields
<%= f.label :amount, "Amount:" %>
<%= f.text_field :amount %>
Here should follow a Select input with content from Ingredient and the POST request should insert the ingredient_id in the column of Quantity.
<%= f.select("ingredient_id", "ingredient_id", Ingredient.all.collect
{|p| [ p.name, p.id ] }, {include_blank: 'Choose'}) %>
getting
NoMethodError in Recipes#new
Showing C:/Sites/4.2/sample_app - Kopie/app/views/recipes/_quantity_fields.html.erb
where line #6 raised:
undefined method `merge' for [["Sugar", 1], ["Butter", 2]]:Array
Any ideas? Thanks!
<%= f.collection_select(:ingredient_id, Ingredient.all, :id, :name) %>
solved the select statement
but how can I create multiple quantities here?