我有以下型號保存它們指向對方的ActiveRecord協會,在一次
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, class_name: 'Assignment', 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, class_name: 'Destination', 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: ...}, ...],
]
}
我知道先保存目的地,然後通過他們迭代設置分配的目標ID可以做的工作,但不知道是否有一個更聰明的方式。
如果我理解你的模式,要通過它的目的地跟蹤的東西。我認爲有更好的方式來安排你的模型關聯。可以請將您的數據庫架構發佈到這三個表中。 –
@佩德羅Assignmet有start_destination_id和goal_destination_id,目的地有cargo_id,這幾乎是要點 – Ryo