Rails 允许的参数未显示在控制台中

Rails permitted parameter not showing up in console

我有一对模型,Preset 和 Plot

class Preset < ApplicationRecord
    belongs_to :user
    has_many :plots, :dependent => :destroy
    accepts_nested_attributes_for :plots, allow_destroy: true
end

class Plot < ApplicationRecord
    belongs_to :preset
    belongs_to :theme, optional: true
end

以及用于编辑预设及其各自绘图的嵌套表单

= form_with(model: @preset, local: true, method: "patch") do |f|
  = label_tag(:name, "Preset name:")
  = text_field_tag(:name, @preset.name)
  %br
  = f.fields_for :plots do |builder|
    %br
    = render 'editplot', f: builder

还有一个 _editplot 部分(它工作正常,但为了完整性而包括在内)

= f.label(:name, "Change plot:")
= f.select(:name, options_for_select([['Existing Plot 1', 'Existing Plot 1'], ['Existing Plot 2', 'Existing Plot 2']]))
= f.label(:_destroy, "Remove plot")
= f.check_box(:_destroy)

我已经在预设控制器中允许我需要的参数如下:

private
        def preset_params
            params.require(:preset).permit(:name, plots_attributes: [:id, :name, :parameter_path, :theme_id, :_destroy])
        end

因此,我希望 :name 参数包含在 preset_params.

控制器中更新方法如下:

def update
        @preset = Preset.find(params[:id])

        puts "name"
        puts params[:name]

        puts "preset params"
        puts preset_params

        if @preset.update(preset_params)
            redirect_to presets_path, notice: 'Preset was successfully updated.'
            return
        else
            render :edit
            return
        end

当我提交表格时,选中的地块按预期被删除。但是,预设本身的名称不会更新。控制台显示参数包括:name参数,它的值是正确的,但是当我输出preset_params时,它没有出现在控制台中。它去哪儿了?

Parameters: {"authenticity_token"=>"15RgDM+SCwfScbQXcHmVGfzo2w8qe972QPdkf/OB9AFeyvtUXdxJpaVGKgCMoLaISYljclmOuIowqrfGyy/Dug==", "name"=>"Edited name", "preset"=>{"plots_attributes"=>{"0"=>{"name"=>"Existing Plot 1", "_destroy"=>"0", "id"=>"3"}, "1"=>{"name"=>"Existing Plot 1", "_destroy"=>"0", "id"=>"4"}}}, "commit"=>"Update Preset", "id"=>"1"}

{"plots_attributes"=><ActionController::Parameters {"0"=><ActionController::Parameters {"id"=>"3", "name"=>"Existing Plot 1", "_destroy"=>"0"} permitted: true>, "1"=><ActionController::Parameters {"id"=>"4", "name"=>"Existing Plot 1", "_destroy"=>"0"} permitted: true>} permitted: true>}

"name" 不在参数中的 "preset" 散列内,请参阅:

Parameters: {
  "name"=>"Edited name", 
  "preset"=>{
    "plots_attributes"=>{
      "0"=>{
        "name"=>"Existing Plot 1", 
        "_destroy"=>"0", 
        "id"=>"3"
      }, 
      "1"=>{
        "name"=>"Existing Plot 1", 
        "_destroy"=>"0", 
        "id"=>"4"
      }
    }
  }, 
  "commit"=>"Update Preset", 
  "id"=>"1"
}

因此,preset_params 不会包括 "name"

你可以试试:

= text_field_tag('preset[name]', @preset.name)

...获取嵌套在 preset 散列中的名称。