代码之家  ›  专栏  ›  技术社区  ›  AntonyZ

Rails 4中动态表单的未经许可的参数

  •  3
  • AntonyZ  · 技术社区  · 11 年前

    我是Rails的新手,并在此基础上构建了一些东西

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

    但我在将数据存储在附加字段中时遇到了问题。。。 我有一个ProductType对象,它有许多ProductField对象。ProductField对象也属于ProductType,Product对象属于ProductType。

    因此,可以很容易地通过构造函数ProductType添加新的动态字段,但当我试图通过Product控制器在这些字段中设置数据时,什么也不会发生。

    我确信这个问题与使用强参数有关,但修复程序已描述 here here 没有帮助。

    产品.rb

    class Product < ActiveRecord::Base
        belongs_to :product_type
        serialize :properties, Hash
    end
    

    产品类型.rb

    class ProductType < ActiveRecord::Base
        has_many :fields, class_name: "ProductField"
        accepts_nested_attributes_for :fields, allow_destroy: true
    end
    

    产品字段.rb

    class ProductField < ActiveRecord::Base
        belongs_to :product_type
    end
    

    产品_控制器.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
    

    产品类型控制程序.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
    

    附言:也许有人在看播客时也遇到了类似的问题?

    1 回复  |  直到 8 年前
        1
  •  12
  •   Beartech    11 年前

    如果你想返回一个嵌套的散列作为参数,你必须将数组中的键命名为 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, :price, :product_type_id, {:properties => [:foo, :bar, :id]})
    end
    

    如果您正在动态生成密钥,并且无法将其编码到 许可证 语句,则需要使用此样式:

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

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

    这不是我的工作,我仍然只是了解 .permit 这样地。这是我使用的博客条目: Strong Parameters by Example