ruby-on-rails - 电影应用的多对多关系
问题描述
我正在创建一个应用程序,用户可以在其中创建电影帖子以及收藏其他用户的电影帖子。我对如何在 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
解决方案
User
您可以使用在和Movie
模型之间创建收藏夹关联has_many :through
class User < ApplicationRecord
has_many :movies
has_many :favorite_movies, class_name: 'Favorite', foreign_key: 'user_id'
has_many :favorites, through: :favorite_movies, source: :movie
end
class Movie < ApplicationRecord
belongs_to :user
end
class Favorite < ApplicationRecord
belongs_to :user
belongs_to :movie
end
它必须以这种方式工作。
现在您可以像这样获得用户的收藏夹:User.first.favorites
推荐阅读
- python - 如何使用虚拟环境突出显示啤酒
- azure - 是否可以在 Function App 引用的外部项目中定义 Azure Functions?
- sql - 如何在自引用键中查找经理级别
- c# - 是否可以将调度程序限制为 Akka.Net 中的一个演员
- c++ - C++ 项目中的 WFDB 库问题(未定义引用)
- sql - 如何使用 Postgresql 复制具有 2 列但具有多个值的 csv 文件
- sql - SQL Server:如果一行的值等于目标值,则返回集合中的所有行
- c++ - 如何强制 boost program_options 严格检查选项?
- c++ - 来自 g++ -fanalyzer 的 std::vector 空指针取消引用
- python - 如何在 .env 文件中保存多个登录名以连接到 postgresql 数据库?