【发布时间】:2019-06-01 18:38:43
【问题描述】:
我希望创建一个关联,其中模型可以由三个不同的实体创建和拥有,但也可以引用其他两个实体。
例如,我有一个 performance 模型,其中三种不同类型的模型可以创建性能:venue、artist、乐队。但是,表演还需要参考其他两个,例如,如果场地创建表演,则需要列出将要表演的艺术家或乐队。如果艺术家创作表演,那么艺术家需要在他/她将要表演的地方放置一个场地。
所以我从这样的事情开始:
class CreatePerformances < ActiveRecord::Migration[6.0]
def change
create_table :performances, id: :uuid do |t|
t.belongs_to :venue, index: true
t.belongs_to :artist, index: true
t.belongs_to :band, index: true
t.timestamps
end
end
end
但是,如果场地所有者创建了一个表演并有两个单独的乐队表演,那么我需要在 band_id 列中有一组乐队。但是当我这样做时 (t.belongs_to :band, type: :uuid, array: true, default: [], index: true) 并在 band_id 数组中添加一个波段,然后执行 band.performances 我得到:ActiveRecord::StatementInvalid (PG::InvalidTextRepresentation: ERROR: malformed array literal:
我可以将关联列设置为数组,并且仍然能够使用 Rails 关联功能,或者这是不可能的,甚至是不好的做法,如果可以,该怎么做?
另外,我正在使用 postgresql,如果您有更优雅的方式来执行上述操作,我将不胜感激。
【问题讨论】:
标签: ruby-on-rails postgresql associations