我是新來的鐵軌和在此基礎上未經許可參數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