【问题标题】:many to many relationships for movie application电影应用的多对多关系
【发布时间】: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


【解决方案1】:

您可以使用has_many :throughUserMovie 模型之间创建收藏夹关联

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-11
    • 2018-06-15
    • 1970-01-01
    • 2011-06-02
    • 2017-08-25
    • 2010-10-30
    • 2014-10-11
    相关资源
    最近更新 更多