活动记录多对多 我应该制作另一个表来保存关系信息吗?



我有albumsartists表,它们应该与许多表相关联:每个专辑可以由多个艺术家拥有,每个艺术家可以有多个专辑。但我需要知道艺术家是主要艺术家还是只是一个贡献者。

目前我只是使用artists表中albums列以分号分隔的字符串保存艺术家 id(格式:3;6;343;56;1(.主要艺术家的ID应该首先出现,其余的只是贡献者。

目前,我通过使用.whereLIKE关键字查询来访问专辑中艺术家的贡献。然后根据此答案过滤数组结果以排除前缀(艺术家 ID(。

@albums_ = Album.where("artists LIKE :prefix", prefix: "%#{params[:id]}%")
@albums_contribute_to = @albums_.select { |album| !album.artists.start_with?("#{params[:id]}") }

有没有更有效的方法来实现这一点?

玩了一下,大的想法是在连接表上放一些额外的信息(在我的示例中,我称之为primary(。然后阅读文档以弄清楚如何告诉ActiveRecord使用它们。

# setup active record
require 'active_record'
ActiveRecord::Base.establish_connection adapter: 'sqlite3', database: ':memory:'
# some tables (migrations / schema)
ActiveRecord::Schema.define do
create_table(:artists) { |t| t.string :name}
create_table(:albums)  { |t| t.string :name }
create_table :appearances do |t|
t.integer :artist_id
t.integer :album_id
t.boolean :primary, default: false # <-- join table specifies who is primary
end
end
# some models
class Artist < ActiveRecord::Base
has_many :appearances
has_many :albums, through: :appearances
end   
class Appearance < ActiveRecord::Base
belongs_to :artist
belongs_to :album
end
class Album < ActiveRecord::Base
# three associations to appearances
has_many :all_appearances,                                   class_name: 'Appearance'
has_many :primary_appearances,  -> { where primary: true  }, class_name: 'Appearance'
has_many :featured_appearances, -> { where primary: false }, class_name: 'Appearance'
# three associations to artists
has_many :all_artists,      through: 'all_appearances',      source: 'artist'
has_many :primary_artists,  through: 'primary_appearances',  source: 'artist'
has_many :featured_artists, through: 'featured_appearances', source: 'artist'
end
# some artists
dre  = Artist.create! name: 'Dr. Dre'
dogg = Artist.create! name: 'Snoop Dogg'
slim = Artist.create! name: 'Eminem'
# some albums
weed = Album.create! name: 'The Chronic 2001',
primary_artists:  [dre],
featured_artists: [dogg, slim]
show = Album.create! name: 'The Eminem Show',
primary_artists:  [slim],
featured_artists: [dre]
# it understands the associations
weed.all_artists.pluck :name      # => ["Dr. Dre", "Snoop Dogg", "Eminem"]
weed.primary_artists.pluck :name  # => ["Dr. Dre"]
weed.featured_artists.pluck :name # => ["Snoop Dogg", "Eminem"]
# might be nice to add similar scoped associations to get from Artist to Album
weed               # => #<Album id: 1, name: "The Chronic 2001">
.primary_artists # => #<ActiveRecord::Associations::CollectionProxy [#<Artist id: 1, name: "Dr. Dre">]>
.first           # => #<Artist id: 1, name: "Dr. Dre">
.albums          # => #<ActiveRecord::Associations::CollectionProxy [#<Album id: 1, name: "The Chronic 2001">, #<Album id: 2, name: "The Eminem Show">]>
.last            # => #<Album id: 2, name: "The Eminem Show">
.primary_artists # => #<ActiveRecord::Associations::CollectionProxy [#<Artist id: 3, name: "Eminem">]>
.first           # => #<Artist id: 3, name: "Eminem">

这是使用连接表的典型情况。如果你想建立那种关系。从长远来看,您正在做的事情只会产生问题,因为您必须将这些信息保存在内存中,这也很慢。

在轨道上的红宝石中,这种关系就像这样的东西:

class Album < ApplicationRecord
has_many :album_artists
has_many :artists, through: :album_artists
end
class AlbumArtist < ApplicationRecord
belongs_to :artist
belongs_to :album
end
class Artist < ApplicationRecord
has_many :album_artists
has_many :albums, through: :album_artists
end   

如果你想避免使用Ruby on rails这样做,你必须实现自定义查询,但规则是相同的,你必须创建某种连接表。

同意约书亚和普热梅克的观点,这是一个简单的解决方案。 以下是使用它的方法:

class Appearance < ActiveRecord::Base
belongs_to :artist
belongs_to :album
# has attribute "primary"
end
class Artist < ActiveRecord::Base
has_many :appearances
has_many :albums, through: :appearances
end
class Album < ActiveRecord::Base
has_many :appearances
has_many :artists, through: :appearances
end
# create album with 2 artists
Album.create(
name: "foo_bar",
appearances: [
Appearance.new(artist: Artist.create(name: "foo"), primary: true),
Appearance.new(artist: Artist.create(name: "bar"))
]
)
# list artists
album = Album.first
album.appearances.order("piramary desc").each do |appearance|
puts "#{appearance.artist.name} #{appearance.primary? ? "(Primary)" : ""}"
end

我真的认为你不需要一个单独的模型来连接AlbumArtist模型。因此,您可以使用来自ActiveRecordhas_and_belong_to_many(HABTM( 方法,该方法用于传递多对多关系。您还需要一个连接 2 个模型的表,并且可以通过迁移轻松创建一个。

我强烈建议您阅读本文。这将对您非常有帮助。

最新更新