【发布时间】:2015-12-11 03:34:34
【问题描述】:
我已阅读这些文件:
- http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-fields_for
- http://edgeapi.rubyonrails.org/classes/ActionController/StrongParameters.html
我的来源:
型号
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"}
【问题讨论】:
-
您应该通过@product.build_product_items 构建您的product_items。它应该工作
-
@AmitBadhekaPykihStaff 它应该是
@product.product_items.build,因为它是has_many关联。
标签: ruby-on-rails