gpt4 book ai didi

ruby-on-rails - 具有多个对象和整数键的 Rails 4 强参数

转载 作者:行者123 更新时间:2023-12-04 12:19:30 24 4
gpt4 key购买 nike

我一次提交一个包含 2-4 个对象的表单,具体取决于父对象的数量。我意识到这可能是非常规的,但我真的希望用户能够在一个表单上一次编辑所有对象。在我的表格上,我正在做:

<%= simple_fields_for "derps[]", derp do |f| %>

<% end %>

然后我在 Controller 中这样做:
def update
@derps = []
@rejects = []
derps_params.each do |key, hash|
derp = Derp.find(key)
derp.assign_attributes(hash)
@rejects << derp unless derp.save
end
if @rejects.empty?
redirect_to @parent, flash: {success: 'Derps were successfully updated.'}
else
@derps = @rejects
render :edit
end
end

假设有两个对象 - 参数通过以下方式:
"derps"=>{"1"=>{"attribute"=>"39", "another_attribute"=>"serp", "a_third_attribute"=>"yerp"}, "2"=>{"attribute"=>"30", "another_attribute"=>"49", }}

我在没有强大参数的情况下在 Rails 3 中工作。我正在升级到 rails 4 并且我正在努力解决如何让它工作 - 我不断收到“Unpermitted parameters: 1, 2”

我假设我需要做类似的事情:
def mashes_params
params.require(:derps).permit(
id: []

或者
def mashes_params
params.require(:derps).permit(
:id,

沿着这些路线的东西,但我已经尝试了所有我能想到的方法,但没有运气。

这里有什么想法吗?

最佳答案

我发现命令行对于调试 Rails 4 中的强参数非常有帮助。 以下是我在控制台中测试您的问题的方法:

rails c # From within your project directory, short for 'rails console'

params = ActionController::Parameters.new( { derps: { 1 => { attribute: 39, another_attribute: "serp" }, 2 => { attribute: 30, another_attribute: 49 } } } )

params # To make sure that the object looks the same

permitted = params.require( :derps ).permit( 1 => [ :attribute, :another_attribute ], 2 => [ :attribute, :another_attribute ] )

permitted # To see what you'd get back in your controller

希望使用此工具,您将能够比反复试验更轻松地调试我的答案没有提供的任何内容。

关于ruby-on-rails - 具有多个对象和整数键的 Rails 4 强参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31945048/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com