我仍然试图在Rails 4中使用强参数,当我尝试为另一个模型提交一个带有params的表单时,我得到了一个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
版本的params而不是symbol
?!?不知道这里的最佳做法是什么??我知道Rails 4模板包括符号化的参数。
发布于 2013-08-13 21:35:45
#symbolize_keys
。rails是为你做的。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上发布一个虚拟应用程序,它会复制这种行为。这样我就可以进一步帮助您了。谢谢
https://stackoverflow.com/questions/18219481
复制相似问题