加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 19:07:27 所属栏目:百科 来源:网络整理
导读:我有以下型号 class Cargo ApplicationRecord has_many :destinations has_many :assignments accepts_nested_attributes_for :destinations accepts_nested_attributes_for :assignmentsendclass Destination ApplicationRecord has_one :assignment_coming
我有以下型号
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“自动地”保存所有记录.此外,您可以让关联提供的查询来处理所有三个表的记录!

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

链接到guide rails has_many_through assoaciton

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读