ruby-on-rails – Rails 4中动态表单的未经许可的参数

我是Rails的新手并基于此构建了一些东西

http://railscasts.com/episodes/403-dynamic-forms

但我在其他字段中存储数据时遇到问题…
我有一个ProductType对象,它有许多ProductField对象. ProductField对象也属于ProductType,Product对象属于ProductType.

因此,可以通过构造函数ProductType轻松添加新的动态字段,但是当我尝试通过Product控件在此字段中设置数据时,没有任何反应.

我确信这个问题与使用强参数有关,但修复描述herehere没有帮助.

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

P.S:观看播客时可能有人遇到类似的问题?

解决方法

如果要将嵌套哈希作为参数返回,则必须将数组中的键命名为permit.
class ProductsController < ApplicationController
def new
@product = Product.new(product_type_id: params[:product_type_id])
end
def product_params
params.require(:product).permit(:name,{:properties => [:foo,:bar,:id]})
end

如果要动态生成密钥并且无法将它们编码到permit语句中,那么您需要使用以下样式:

def product_params
  params.require(:product).permit(:name,:product_type_id).tap do |whitelisted|
    whitelisted[:properties] = params[:product][:properties]
  end
end

对于新用户来说,这不是最友好的代码,我刚刚在UW完成了3门课程导轨证书,他们甚至从未覆盖.tap.

这不是我的工作,我仍然只是理解像这样的.permit的深层部分.这是我使用的博客条目:Strong Parameters by Example

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...