我有以下型号
- class Cargo < ApplicationRecord
- has_many :destinations
- has_many :assignments
- accepts_nested_attributes_for :destinations
- accepts_nested_attributes_for :assignments
- end
- class Destination < ApplicationRecord
- has_one :assignment_coming_to_me,class_name: 'Assignment',foreign_key: 'arrive_destination_id'
- has_one :assignment_leaving_me,foreign_key: 'start_destination_id'
- end
- class Assignment < ApplicationRecord
- belongs_to :start_from,class_name: 'Destination',foreign_key: 'start_destination_id'
- belongs_to :arrive_at,foreign_key: 'arrive_destination_id'
- end
提供视觉图像,就像这样
- +-------------+
- +---| Destination |
- | +-------------+---+ <= start_from
- | | +------------+
- | +---| Assignment |
- | | +------------+
- +-------+ | +-------------+---+ <= arrive_at
- | Cargo | --+---| Destination |
- +-------+ | +-------------+---+ <= start_from
- | | +------------+
- | +---| Assignment |
- | | +------------+
- | +-------------+---+ <= arrive_at
- +---| Destination |
- | +-------------+---+
- | |
- . .
- . .
现在,有没有办法一次创建整个记录,给定这样的参数? (假设目的地和分配彼此相关,就像参数数组的顺序一样)
- {
- cargo: [
- destinations_attributes: [{place_id: ..},{place_id: ...},...],assignments_attributes: [{assignee_id: ..},{assignee_id: ...},]
- }
我知道首先保存目的地然后迭代它们来设置Assignment的destination_id可以完成这项工作,但想知道是否有更聪明的方法.
解决方法
好吧,不知道你的问题的细节我会回答我认为这将是一个“苛刻”的解决方法.
使用has_many通过关联,您将拥有:
货物通过任务有许多目的地.
目的地有许多货物通过分配.
分配包含货物和目的地外键.
如果您需要有关目的地顺序的信息,您可以根据Assignment的创建时间戳查询记录.
这里有一个example-of-has-many-through-using-nested-attributes.我相信你可以让rails“自动地”保存所有记录.此外,您可以让关联提供的查询来处理所有三个表的记录!
让我知道你的想法!
祝好运!