首页 > 解决方案 > 电影应用的多对多关系

问题描述

我正在创建一个应用程序,用户可以在其中创建电影帖子以及收藏其他用户的电影帖子。我对如何在 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-railsmany-to-many

解决方案


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


推荐阅读