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

问题描述 投票:0回答:1

我有一对模型,预设和绘图

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参数包含在预置参数中。

控制器中的更新方法如下:

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参数,并且它的值正确,但是当我输出预设参数时,它不会显示在控制台中。它去了哪里?

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>}
ruby-on-rails strong-parameters form-with
1个回答
1
投票

["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哈希中的名称。

© www.soinside.com 2019 - 2024. All rights reserved.