嵌套属性 2 层深时从控制器获取参数

Fetch params from controller when nesting attributes 2 levels deep

我的 Pack 模型有线,线又包含项目,包和线都接受它们包含的集合的嵌套属性。

以下是模型:

Class Pack < ApplicationRecord
   has_many :pack_lines, dependent: :destroy
   accepts_nested_attributes_for :pack_lines, allow_destroy: true
end

Class PackLine < ApplicationRecord
   belongs_to :pack
   has_many :pack_line_items, dependent: :destroy
   accepts_nested_attributes_for :pack_line_items, allow_destroy: true
end

Class PackLineItem < ApplicationRecord
   belongs_to :pack_line
end

我花了很长时间才找到用于 permit 控制器中嵌套嵌套参数的正确语法。

经过大量的思考和文档阅读,这是我想出的:

# In controllers/packs_controller.rb
def pack_params
   params.require(:pack).permit(
      :name,
      pack_lines_attributes: [
         :id,
         :_destroy,
         {
           pack_line_items_attributes: [
             :id,
             :_destroy
           ]
         }
      ]
   )
end

希望对您有所帮助!

您可以允许这样的嵌套属性。

params.require(:pack).permit(
  :name,
  pack_lines_attributes: [
    :id, :_destroy, pack_line_items_attributes: [
         :id, :_destroy
    ]
  ]
)

它们对 has_manyhas_one 的工作方式类似。如果 has_onepack_line_attributes [:id]

你可能需要单数化