你可以使用一个连接表模型,可以:
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
现在,或安慰。通过user.save
现在album = Album.find_or_create_by(params)
与专辑副用户user.albums << album
&然后将其保存到看到用户的:你可以这样做:
- 创建用户:
user = User.create(params)
- 查找或创建一个相册专辑。你可以这样做:
User.take.albums
看到一个特定专辑的用户,你可以做 Album.take.users
希望这回答了你的问题。
欲了解更多信息看看导轨指南: http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association