[英]Rails4: ForbiddenAttributesError on nested parent's params
我仍在嘗試圍繞Rails 4中的“ 強參數” ( Strong Parameters)解決問題 。嘗試為它belongs_to
另一個模型的參數提交帶有表單的表單時,遇到了ActiveModel::ForbiddenAttributesError
。
Product :has_many DiskFiles
經過一番偵查,我意識到我需要先對自己的鍵進行符號化,然后再將其傳遞給類似的東西,否則我將得到ForbiddenAttributesError
。 所以這將工作:
#disk_files_controller.rb
def update
product = @disk_file.create_product(params[:product].symbolize_keys) if params[:product]
...
end
檢查參數[:產品]:
>> params[:product]
=> {"title"=>"Registration Test5", "year"=>"1988", "region_id"=>"7"}
無論哪種情況,我都允許這些參數(以及其他):
def disk_file_params
params.require(:disk_file).permit(:filename, :file_path, :title,
:product, :year, :region_id)
end
由於所有參數最初都是strings
因此我們應該允許使用string
版本而不是symbol
?!嗎? 不確定此處的最佳做法是什么?!? 我知道Rails 4模板包含符號化的參數。
#symbolize_keys
。 rails為您做到這一點。 您可以通過以下方式在StrongParams中使用嵌套屬性
params.require(:model_name_here).permit(:attribute1, :attribute2, :attribute3, nested_model_name_here: [:attribute1, :attribute2, :attribute3])
因此您可以執行以下操作:
params.require(:product).permit(:title, :year, :region_id, disk_file: [:filename, :file_path, :title,
:product, :year, :region_id])
這是假設disk_file
的屬性嵌套在product
以進行params哈希處理。 如果仍然出現錯誤,請在github上發布一個虛擬應用程序,以重現此行為。 因此我可以為您提供進一步的幫助。 謝謝
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.