Rails associations using an array as the foreign_id

Dar*_*isa 0 postgresql ruby-on-rails associations

I am looking to create an association where a model can be created and owned by three different entities but also references the other two entities.

For example, I have a performance model where three different types of models can create a performance: venue, artist, band. However, the performance also needs to reference the other two e.g if a venue creates a performance, it needs to list an artist or a band that will be performing. And if an artist creates a performance, then the artist needs to put a venue where he/she will be performing.

So I am starting with something like this:

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
Run Code Online (Sandbox Code Playgroud)

However, if a venue owner creates a performance and has two separate bands performing then I would need to have an array of bands in the band_id column. But when I do that (t.belongs_to :band, type: :uuid, array: true, default: [], index: true) and add a band to the band_id array and then do band.performances I get: ActiveRecord::StatementInvalid (PG::InvalidTextRepresentation: ERROR: malformed array literal:

Can I make an association column an array and still be able to use the Rails association features or is that not possible or even bad practice, and if so how?

Also, I am using postgresql and if you have a more elegant ways of doing the above that would also be appreciated.

ari*_*uod 5

I guess it's better to use a has_many relationship.

如果一场表演可以有很多乐队演奏,那么它就不“属于”一个乐队,而是“有很多”乐队。

因此,您可能会在演出和乐队之间使用“拥有并属于许多人”或“拥有许多:贯穿”关系。在此处检查差异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
Run Code Online (Sandbox Code Playgroud)

您需要一个表,因此添加一个执行此操作的模拟:

create_table :bands_performances, id: false do |t|
  t.references :band, index: true
  t.references :performance, index: true
end
Run Code Online (Sandbox Code Playgroud)

https://guides.rubyonrails.org/association_basics.html#creating-join-tables-for-has-and-belongs-to-many-associations

查看指南,如果您需要其他字段,则可能需要连接模型并使用has_many:through。您比任何人都了解上下文。