【问题标题】:How to use accepts_nested_attributes_for with rails?如何在rails中使用accepts_nested_attributes_for?
【发布时间】:2015-12-11 03:34:34
【问题描述】:

我已阅读这些文件:

我的来源:

型号

app/models/product.rb

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

app/models/product_item.rb

class ProductItem < ActiveRecord::Base
  belongs_to :product
end

控制器

app/controllers/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

查看

app/views/products/_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日志:

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"}

【问题讨论】:

  • 您应该通过@p​​roduct.build_product_items 构建您的product_items。它应该工作
  • @AmitBadhekaPykihStaff 它应该是@product.product_items.build,因为它是has_many 关联。

标签: ruby-on-rails


【解决方案1】:

您的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

【讨论】:

    【解决方案2】:

    更新您的控制器操作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

    【讨论】:

    • 谢谢。我试过你的方法,但结果是一样的。即使我看到nested_form,它似乎也很旧,只适用于 Rails 3。现在我正在使用 Rails 4。
    • 您可以在这里发布您在提交请求时获得的请求参数
    • 你能从 Rails 控制台日志中发布同样的内容吗?其实我想看看rails控制台中params hash的结构和控制器动作的日志。谢谢
    • 我已经发布了rails日志信息。除了格式之外,它们是相同的。
    猜你喜欢
    • 1970-01-01
    • 2011-02-17
    • 1970-01-01
    • 1970-01-01
    • 2011-10-07
    • 2012-05-10
    • 2010-11-16
    • 1970-01-01
    • 2012-11-09
    相关资源
    最近更新 更多