繁体   English   中英

Rails - 将嵌套参数从表单传递到 controller

[英]Rails - Passing nested params from a form into a controller

我正在使用 Rails Strong 参数来帮助允许嵌套输入参数,并且似乎遇到了问题。 我在这里关注accepts_nested_attributes_for的 rails 文档,但运气不佳,因为我的数据库关系有点复杂。 非常感谢 Rails 社区在将我的输入传递到后端的帮助。

我的数据库关系:

票证 Model:

class Ticket < ActiveRecord::Base
  belongs_to :device, polymorphic: true
end

设备 Model:

class Device < ActiveRecord::Base
  has_many :tickets, as: :device
  has_many :addresses, foreign_key: 'device_id'

  accepts_nested_attributes_for :addresses
end

地址 Model:

class Address < ActiveRecord::Base
  belongs_to :device
end

有了这些关系,我就有了一个创建工单的表单。 该表单应允许在表单上指定用于创建Address对象的address输入列表,并且addresses列表进一步与Device本身相关联。

以下是我在创建Ticket期间传递这些嵌套输入参数的方式:

票证 controller:

def create
  ticket = Ticket::Creator.call(ticket_params: ticket_params)
  redirect_to path(ticket)
end

private

def ticket_params
  params.require(:ticket).permit(
    {
      device: %i[#device_params],
      address_attributes: %i[name] # name is input by the user.
    }
  )
end

按照我现在设置的方式, controller 应该首先创建一个 Ticket,然后创建一个Device和一个与Device相关的Address对象列表。 但我似乎无法阅读表单上的address_attributes

这是我在表格上抓取它们的方式:

name: 'ticket[device][addresses][][name]'

我在这里做错了什么吗? 如果我可以在这里提供更多信息,请告诉我。

您应该像这样使用 accept_nested_attributes :

class Ticket < ActiveRecord::Base
   belongs_to :device, polymorphic: true
   accepts_nested_attributes_for :device
end 

class Device < ActiveRecord::Base
  has_many :tickets, as: :device
  has_many :addresses, foreign_key: 'device_id'

  accepts_nested_attributes_for :addresses
end

class Address < ActiveRecord::Base
  belongs_to :device
end

使用 model 设置,您可以在 TicketController 中使用具有嵌套这样的强参数:

def create
  ticket = Ticket.create(ticket_params)
  redirect_to path(ticket)
end

private

def ticket_params
  params.require(:ticket).permit(
      device_attributes: [
          addresses_attributes: [:name]
      ]          
  )
end

请记住,要创建多个地址,您需要传递以下地址属性: ticket[device_attributes][addresses_attributes][][name]

我建议你过度考虑你的多态关系。 由于这种关系,您需要在您的ticket_params中传递一个device_type

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM