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

时间:2015-03-24 01:09:42

标签: ruby-on-rails attributes params cookbook

有人知道如何在控制器new中处理这些属性并创建动作吗?

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

1 个答案:

答案 0 :(得分:1)

我换了:

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

使用:

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

并在fields_for之后将提交操作置于表单级别:

<%= f.submit "Create" %>