我一次提交一个包含2-4个对象的表单,具体取决于父项的数量.我意识到这可能是非常规的,但我真的希望用户能够在一个表单上一次编辑所有对象.在我的表格上,我正在做:
<%= simple_fields_for "derps[]",derp do |f| %> <% end %>
然后我在控制器中这样做:
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,我正在努力解决这个问题 – 我不断得到“未经许可的参数: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