ruby-on-rails – 保存ActiveRecord的关联,这些关联一次指向对方

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 保存ActiveRecord的关联,这些关联一次指向对方前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有以下型号
  1. class Cargo < ApplicationRecord
  2. has_many :destinations
  3. has_many :assignments
  4. accepts_nested_attributes_for :destinations
  5. accepts_nested_attributes_for :assignments
  6. end
  7.  
  8. class Destination < ApplicationRecord
  9. has_one :assignment_coming_to_me,class_name: 'Assignment',foreign_key: 'arrive_destination_id'
  10. has_one :assignment_leaving_me,foreign_key: 'start_destination_id'
  11. end
  12.  
  13. class Assignment < ApplicationRecord
  14. belongs_to :start_from,class_name: 'Destination',foreign_key: 'start_destination_id'
  15. belongs_to :arrive_at,foreign_key: 'arrive_destination_id'
  16. end

提供视觉图像,就像这样

  1. +-------------+
  2. +---| Destination |
  3. | +-------------+---+ <= start_from
  4. | | +------------+
  5. | +---| Assignment |
  6. | | +------------+
  7. +-------+ | +-------------+---+ <= arrive_at
  8. | Cargo | --+---| Destination |
  9. +-------+ | +-------------+---+ <= start_from
  10. | | +------------+
  11. | +---| Assignment |
  12. | | +------------+
  13. | +-------------+---+ <= arrive_at
  14. +---| Destination |
  15. | +-------------+---+
  16. | |
  17. . .
  18. . .

现在,有没有办法一次创建整个记录,给定这样的参数? (假设目的地和分配彼此相关,就像参数数组的顺序一样)

  1. {
  2. cargo: [
  3. destinations_attributes: [{place_id: ..},{place_id: ...},...],assignments_attributes: [{assignee_id: ..},{assignee_id: ...},]
  4. }

我知道首先保存目的地然后迭代它们来设置Assignment的destination_id可以完成这项工作,但想知道是否有更聪明的方法.

解决方法

好吧,不知道你的问题的细节我会回答我认为这将是一个“苛刻”的解决方法.

使用has_many通过关联,您将拥有:

货物通过任务有许多目的地.

目的地有许多货物通过分配.

分配包含货物和目的地外键.

如果您需要有关目的地顺序的信息,您可以根据Assignment的创建时间戳查询记录.

这里有一个example-of-has-many-through-using-nested-attributes.我相信你可以让rails“自动地”保存所有记录.此外,您可以让关联提供的查询来处理所有三个表的记录!

让我知道你的想法!
祝好运!

链接guide rails has_many_through assoaciton

猜你在找的Ruby相关文章