Active Record Associations 以防止重复的数据库条目

Active Record Associations to prevent duplicate database entries

我正在 Rails 应用程序上设置 Ruby,用户将在其中拥有相册集。我最初的想法是用一个简单的 User has_many Albums 和 Albums belongs to Users 来设置它。这里出现的问题是专辑 table 将有重复的条目,仅以 user_id.

区分
id  | album_name  | artist_id |         created_at         |         updated_at         | user_id 
-----+-------------+-----------+----------------------------+----------------------------+---------
   2 | SuperRando |   3       | 2015-11-13 00:03:51.790759 | 2015-11-13 00:03:51.790759 |  1       
   3 | SuperRando |   3       | 2015-11-13 00:19:08.438907 | 2015-11-13 00:19:08.438907 |  2      

那么最好的行动方案是什么,这样我就可以拥有一张包含所有独特专辑的专辑 table?

您可以使用连接对其进行建模 table:

class Album < ActiveRecord::Base
  has_many :user_albums
  has_many :users, through: :user_albums
end

class User < ActiveRecord::Base
  has_many :user_albums
  has_many :albums, through: :user_albums
end

class UserAlbum < ActiveRecord::Base
  belongs_to :user
  belongs_to :album
end

因此,您的架构会像这样:

create_table "albums", force: :cascade do |t|
    t.string   "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "user_albums", force: :cascade do |t|
    t.integer  "user_id"
    t.integer  "album_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "users", force: :cascade do |t|
    t.string   "email"
    t.string   "first_name"
    t.string   "last_name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

现在,您将在控制器或控制台中调用此代码的方式。你可以这样做:

  1. 创建用户:user = User.create(params)
  2. 查找或创建相册:album = Album.find_or_create_by(params)
  3. 将用户与该相册关联 user.albums << album,然后按 user.save
  4. 保存

现在可以查看用户的相册。你可以做: User.take.albums

要查看特定相册的用户,您可以这样做 Album.take.users

希望这能回答您的问题。

有关详细信息,请查看 rails 指南: http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association