【问题标题】:Active Record Associations to prevent duplicate database entries活动记录关联以防止重复的数据库条目
【发布时间】:2015-11-15 14:36:58
【问题描述】:

我正在设置一个 Ruby on Rails 应用程序,其中用户将拥有一个专辑集合。我最初的想法是用一个简单的用户 has_many 专辑和专辑属于用户来设置它。这里出现的问题是Album表会有重复的条目,只用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      

那么最好的做法是什么,这样我才能拥有一张包含所有独特专辑的专辑表?

【问题讨论】:

    标签: ruby-on-rails rails-activerecord psql


    【解决方案1】:

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

    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 &lt;&lt; album 关联,然后将其保存为user.save

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

    要查看特定相册的用户,您可以执行以下操作 Album.take.users

    希望这能回答您的问题。

    有关更多信息,请查看导轨指南: http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-04
      • 2016-07-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多