ActiveRecord我应该创建另一个表以保存关系信息吗?

时间:2018-05-26 00:09:53

标签: sql ruby-on-rails ruby postgresql rdbms

我有albumsartists个表格,这些表格应该与多个参与者有关:每个专辑可以由多个艺术家拥有,每个艺术家可以拥有多个专辑。但我需要知道艺术家是主要艺术家还是仅仅是贡献者。

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

目前,我通过查询.whereLIKE关键字在相册中访问艺术家的贡献。然后根据this回答过滤数组结果以排除前缀(艺术家ID)。

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

有没有更有效的方法来实现这个目标?

4 个答案:

答案 0 :(得分:3)

使用连接表是典型的情况。如果你想创造那种关系。你所做的只会在长期内产生问题,因为你必须将这些信息保存在内存中,这也很慢。

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

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   

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

答案 1 :(得分:3)

稍微玩了一下,最重要的想法是在连接表上添加一些额外的信息(在我的例子中,我称之为primary)。然后阅读docs以了解如何告诉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">

答案 2 :(得分:2)

同意Joshua和Przemek,这是一个简单的解决方案。这是如何使用它:

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

答案 3 :(得分:0)

我真的不认为你需要一个加入keysymdef.hAlbum的模型。因此,您可以使用来自Artist的{​​{1}}(HABTM)方法,该方法用于传递多对多关系。您还需要一个连接2个模型的表,您可以轻松地创建一个具有迁移的表。

我强烈建议您阅读此article。这对你真的很有帮助。