【问题标题】:Rails 4.2 Create ActiveRecord object with nested paramsRails 4.2 使用嵌套参数创建 ActiveRecord 对象
【发布时间】:2016-04-23 00:41:03
【问题描述】:

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

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

【问题讨论】:

    标签: ruby-on-rails attributes params cookbook


    【解决方案1】:

    我换了:

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

    与:

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

    fields_for之后将提交动作放到表单级别:

    <%= f.submit "Create" %>
    

    【讨论】:

      猜你喜欢
      • 2014-09-05
      • 2010-10-25
      • 1970-01-01
      • 2013-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-22
      相关资源
      最近更新 更多