0

Does anybody know how to handle these attributes in the controllers new and create action?

(byebug) params
{"utf8"=>"V", "authenticity_token"=>"Wex9nnFigOviySzjfPN6zw==",
"recipe"=>{"name"=>"Cupcake"}, 
"name"=>{"ingredient_id"=>"2"}, 
"quantity"=>{"amount"=>"zwei"}, 
"commit"=>"Create", "controller"=>"recipes", "action"=>"create"}

I don't know how to create the quantities record with the value from Ingredient in recipe#new

("name"=>{"ingredient_id"=>"2")

Two records should be created (Recipe and Quantity).

Recipe
  name

Quantity
  ingredient_id 
  recipe_id 
  amount

Ingredient
  name

class Recipe < ActiveRecord::Base
  belongs_to :user
  has_many :quantities
  has_many :ingredients, through: :quantities
  accepts_nested_attributes_for :quantities, :reject_if => :all_blank, :allow_destroy => true
  accepts_nested_attributes_for :ingredients
end

class Ingredient < ActiveRecord::Base
  has_many :quantities
  has_many :recipes, :through => :quantities
end

class Quantity < ActiveRecord::Base
  belongs_to :recipe
  belongs_to :ingredient
  accepts_nested_attributes_for :ingredient, :reject_if => :all_blank
end

<%= form_for(@recipe) do |f| %>
<%= f.label :name %>
<%= f.text_field :name %>
  <%= form_for(@recipe.quantities.build) do |g| %>
    <%= select("name", "ingredient_id", Ingredient.all.collect {|p| [ p.name, p.id ] }, {include_blank: 'Auswählen'}) %>
    <%= g.label :amount %>
    <%= g.text_field :amount %>
    <%= g.submit "Create" %>
  <% end %>
<% end %>
Stef Hej
  • 1,367
  • 2
  • 14
  • 23

1 Answers1

1

I replaced:

<%= form_for(@recipe.quantities.build) do |g| %>

with:

<%= f.fields_for :quantities, @recipe.quantities.build do |g| %>

And put submit action to form level after fields_for:

<%= f.submit "Create" %>
Stef Hej
  • 1,367
  • 2
  • 14
  • 23
Alejandro Babio
  • 5,189
  • 17
  • 28