我是新来的铁轨和在此基础上未经许可参数4
http://railscasts.com/episodes/403-dynamic-forms
,但我有在其他字段中存储数据的问题...... 我有一些建具有多个ProductField对象的ProductType对象。 ProductField对象也属于ProductType,Product对象属于ProductType。
因此,可以通过构造函数ProductType轻松地添加新的动态字段,但是当我尝试通过产品控制器在此字段中设置数据时,什么都不会发生。
我相信这个问题与使用强参数有关,但修复描述here和here没有帮助。
product.rb
class Product < ActiveRecord::Base
belongs_to :product_type
serialize :properties, Hash
end
product_type.rb
class ProductType < ActiveRecord::Base
has_many :fields, class_name: "ProductField"
accepts_nested_attributes_for :fields, allow_destroy: true
end
product_field.rb
class ProductField < ActiveRecord::Base
belongs_to :product_type
end
products_controller.rb
class ProductsController < ApplicationController
def new
@product = Product.new(product_type_id: params[:product_type_id])
end
def product_params
params.require(:product).permit(:name, :price, :product_type_id, {:properties => []})
end
product_type_controller.rb
class ProductTypesController < ApplicationController
def product_type_params
params.require(:product_type).permit(:name, fields_attributes: [:id, :name, :field_type, :required, :product_type_id])
end
在控制台日志: 不允许的参数:性能
Started PATCH "/products/4" for 127.0.0.1 at 2013-10-04 22:54:59 +0400
Processing by ProductsController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"my3ra60OUXexmmguk2eqRetizx3tWPMq04Z2PnODJMQ=", "product"=>{"product_type_id"=>"1", "name"=>"Product1", "properties"=>{"gjfghjf"=>"123", "123"=>[""]}, "price"=>"10"}, "commit"=>"Update Product", "id"=>"4"}
Product Load (0.3ms) SELECT "products".* FROM "products" WHERE "products"."id" = ? LIMIT 1 [["id", "4"]]
Unpermitted parameters: properties
PS:也许有人看的时候遇到了类似的问题播客?
你可以发布你的表单代码吗?我看到你在返回参数中得到了这个:'“properties”=> {“gjfghjf”=>“123”,“123”=> [“”]}。属性以两个项目的散列形式出现,其中一个是数组。在您的product_params中,它期望基于写入方式的允许标量值数组。 Railscast最初是使用Rails 4完成的吗? – Beartech
如果你想测试它是如何在表单代码或'permit'语句中构造参数的问题,你可以这样做:'params.require(:product).permit!'。它会将所有内容列入白名单。适合测试,但对安全性非常不利,所以您需要在某个时刻对其进行分类。 – Beartech
Yeap,params.require(:product).permit!真的在工作,但这对安全非常不利,你很对.. – AntonyZ