Rails 协会使用数组作为 foreign_id
Rails associations using an array as the foreign_id
我希望创建一个关联,其中一个模型可以由三个不同的实体创建和拥有,但也可以引用其他两个实体。
例如,我有一个 performance 模型,其中三种不同类型的模型可以创建性能:venue、艺术家,乐队。但是,表演还需要参考其他两个,例如,如果场地创建表演,则需要列出将要表演的艺术家或乐队。而如果一个艺术家创作了一场表演,那么艺术家需要在 he/she 表演的地方放置一个场地。
所以我从这样的事情开始:
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,如果您有更优雅的方法来执行上述操作,我们也将不胜感激。
我想最好使用has_many关系。
如果一场演出可以有很多乐队演奏,那么它就不是 "belongs to" 个乐队,而是 "has many" 个乐队。
因此您可以在表演和乐队之间使用 "has and belongs to many" 或 "has many :through" 关系。在此处检查差异 https://guides.rubyonrails.org/association_basics.html#choosing-between-has-many-through-and-has-and-belongs-to-many
两者中最容易配置的是 HABTM:
class Band
has_and_belongs_to_many :performances
class Performance
has_and_belongs_to_many :bands
您需要一个 table,所以添加一个 miration 来执行此操作:
create_table :bands_performances, id: false do |t|
t.references :band, index: true
t.references :performance, index: true
end
查看指南,如果您需要额外的字段,您可能需要一个连接模型并使用 has_many :through。你比谁都了解上下文。
我希望创建一个关联,其中一个模型可以由三个不同的实体创建和拥有,但也可以引用其他两个实体。
例如,我有一个 performance 模型,其中三种不同类型的模型可以创建性能:venue、艺术家,乐队。但是,表演还需要参考其他两个,例如,如果场地创建表演,则需要列出将要表演的艺术家或乐队。而如果一个艺术家创作了一场表演,那么艺术家需要在 he/she 表演的地方放置一个场地。
所以我从这样的事情开始:
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,如果您有更优雅的方法来执行上述操作,我们也将不胜感激。
我想最好使用has_many关系。
如果一场演出可以有很多乐队演奏,那么它就不是 "belongs to" 个乐队,而是 "has many" 个乐队。
因此您可以在表演和乐队之间使用 "has and belongs to many" 或 "has many :through" 关系。在此处检查差异 https://guides.rubyonrails.org/association_basics.html#choosing-between-has-many-through-and-has-and-belongs-to-many
两者中最容易配置的是 HABTM:
class Band
has_and_belongs_to_many :performances
class Performance
has_and_belongs_to_many :bands
您需要一个 table,所以添加一个 miration 来执行此操作:
create_table :bands_performances, id: false do |t|
t.references :band, index: true
t.references :performance, index: true
end
查看指南,如果您需要额外的字段,您可能需要一个连接模型并使用 has_many :through。你比谁都了解上下文。