Допустимый параметр Rails не отображается в консоли

У меня есть пара моделей 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>}

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 хэш.

Другие вопросы по тегам