如何在rails中使用accepts_nested_attributes_for?

时间:2015-09-15 02:02:05

标签: ruby-on-rails

我已阅读这些文件:

我的来源:

模型

应用程序/模型/ product.rb

class Product < ActiveRecord::Base
  has_many :product_items, foreign_key: :product_id, :dependent => :destroy
  accepts_nested_attributes_for :product_items
end

应用程序/模型/ product_item.rb

class ProductItem < ActiveRecord::Base
  belongs_to :product
end

控制器

应用程序/控制器/ products_controller.rb

class ProductController < ApplicationController
  def new
    @product = Product.new
  end

  def create
    @product = Product.new(product_params)
    respond_to do |format|
      if @product.save
        format.html { redirect_to root_path }
      else
        format.html { render :new }
      end
    end
  end

  private

  def product_params
    params.require(:product).permit(:name, product_items_attributes: [ :description ])
  end
end

查看

应用程序/视图/产品/ _form.html.erb

<%= form_for(product, url: path) do |f| %>
  <%= f.label :name %>
  <%= f.text_field :name %>

  <%= f.fields_for :product_items do |item_form| %>
    <%= item_form.label :description %>
    <%= item_form.text_field :description %>
  <% end %>

  <%= f.submit 'Submit' %>
<% end %>

我可以将产品数据保存到数据库中,但不能保存product_items。

修改

提交表单后添加我的帖子数据:

utf8:✓
authenticity_token:c5sdmoyLoN01Fxa55q6ahTQripx0GZvWU/d27C]asfdawofX9gw==
product[name]:apple
product[product_items][description]:good
commit:Submit

编辑2

添加rails log:

Started POST "/products" for 10.0.2.2 at 2015-09-15 13:00:57 +0900
Processing by ProductController#create as HTML
I, [2015-09-15T13:00:58.039924 #28053]  INFO -- :   Parameters: {"utf8"=>"✓", "authenticity_token"=>"bilBzgOLc2/ZRUFhJORn+CJvCHkVJSsHQTg1V/roifoHxi9IRA==", "product"=>{"name"=>"apple", "product_items"=>{"description"=>"good"}}, "commit"=>"Submit"}

2 个答案:

答案 0 :(得分:2)

您的new方法应如下所示,以便保存product_items

def new
  @product = Product.new
  @product.product_items.build
end

您还应更改product_params,如下所示 更新 ,以便在以后中正常使用。

def product_params
  params.require(:product).permit(:name, product_items_attributes: [ :id, :description ])
end

答案 1 :(得分:0)

更新您的控制器操作product_params

def product_params
  params.require(:product).permit(:name, product_items_attributes: [:id, :description, :_destroy ])
end

您可以使用nested_form gem来为您提供完整的演示和功能控制。这是链接https://github.com/ryanb/nested_form