【发布时间】:2020-01-22 21:35:50
【问题描述】:
我正在创建一个应用程序,用户可以在其中创建电影帖子以及收藏其他用户的电影帖子。我对如何在 rails 后端设置多对多关系感到困惑。
用户有很多电影,也可以有很多收藏(这是电影发布,但他们只是单击一个按钮将它们添加到他们的收藏部分),并且许多用户可以收藏同一部电影。
我现在建立关系和模型的方式.....
class CreateFavorites < ActiveRecord::Migration[5.2]
def change
create_table :favorites do |t|
t.integer :user_id
t.integer :movie_id
end
end
end
class Favorite < ApplicationRecord
belongs_to :user
end
class Movie < ApplicationRecord
belongs_to :user
has_many :comments
belongs_to :favorite
end
class CreateMovies < ActiveRecord::Migration[5.2]
def change
create_table :movies do |t|
t.string :name
t.string :genre
t.string :rating
t.string :image
t.string :watch_link
t.integer :user_id
end
end
end
class User < ApplicationRecord
has_secure_password
has_many :movies
has_many :comments
has_many :favorites
end
class CreateUsers < ActiveRecord::Migration[5.2]
def change
create_table :users do |t|
t.string :name
t.string :email
t.string :username
t.string :password_digest
end
end
end
【问题讨论】:
-
汉娜,你试过我的答案了吗?
-
我刚看到答案,我现在就开始研究它,我会告诉你进展如何,谢谢你的帮助
标签: ruby-on-rails many-to-many