Rails 4.2 使用嵌套参数创建 ActiveRecord 对象

Rails 4.2 Create ActiveRecord object with nested params

有人知道如何在控制器新建和创建操作中处理这些属性吗?

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

我不知道如何使用配方中成分的值创建数量记录#new

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

应创建两条记录(配方和数量)。

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 %>

我替换了:

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

与:

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

并在 fields_for:

之后将提交操作放到表单级别
<%= f.submit "Create" %>