如何设计 has_many through: in rails 6 with Characters and Movies

How to design a has_many through: in rails 6 with Characters and Movies

我想知道你是否可以帮我解决这个问题。我已经挣扎了两天了。 我正在尝试为 rails 上的电影、演员和工作室构建模型。 所以到目前为止,我得到的是 STUDIO has_many 电影和许多角色(如 MCU 中有钢铁侠、雷神、绿巨人等角色,或者 DCU 中有蝙蝠侠、小丑等...)。还有,一个MOVIEhas_many个角色通过一个STUDIO。还有一个角色 has_many 通过工作室拍摄电影。

所以我的设计是这样的(尝试用postgresql数据库设计)

rails g model studio name:string movies_ids:Array characters_ids:Array #movies_ids will hold an array of all the ids of the movies that 
                                                                       belong to the studio, same goes for characters_ids

rails g model movie title:string studio_id:integer characters_ids:Array #a movie belongs to only one studio, 
                                                                        but has many characters, so an array of all the characters_ids.

rails g model character name:string studio_id:integer movies_ids:Array #a character belongs to a single studio but can appear in many movies, 
                                                                        so an array of movies_ids

这个模型设计的对吗?我错过了什么吗?到现在你可能已经意识到我是新手了。

所以,在那之后,在我的模型中我会有类似的东西:

class Character < ApplicationRecord
    belongs_to :studio
    has_many :movies, through: :studio
end

class Movie < ApplicationRecord
    belongs_to :studio
    has_many :characters, through: :studio
end

class Studio < ApplicationRecord
    has_many :movies
    has_many :characters
end

我想要实现的是能够说 Studio.Movie.all() 并从工作室检索所有电影。 还有 Movie.characters.all() 并从电影中检索所有角色 并且 Character.movies.all() 还检索角色出现过的所有电影。 以后我会有很多工作室,DCU、MCU、Warner、Pixar等等...

如果您能稍微指导我或至少为我指出正确的方向,我将不胜感激。我很难掌握如何实现这一目标。我一直在使用不同的 youtube 视频来指导我,但是 none 他们中的一些人正在设计我正在尝试做的事情。

对于你想要的,终端上 运行 的代码是:

rails g model studio name:string      
rails g model movie title:string studio:belongs_to
rails g model character name:string studio:belongs_to

无需创建 characters_ids:Array,因为当您添加 has_many :characters Rails 时会处理其余部分。

更新:

  • Movie and Characters has a join table
  • Studio has many Movies
  • Studio has many Characters.

命令:

rails g model Studio name:string      
rails g model Movie title:string studio:belongs_to
rails g model Character name:string studio:belongs_to
rails g model MovieCharacter character:belongs_to movie:belongs_to

模特:

class Character < ApplicationRecord
   belongs_to :movie
   has_many :character_movies
   has_many :movies, through: :character_movies
end

class Movie < ApplicationRecord
    belongs_to :studio
    has_many :character_movies
    has_many :characters, through: :character_movies
end

class Studio < ApplicationRecord
    has_many :movies
    has_many :characters
end

class MovieCharacter < ApplicationRecord
    belongs_to :movies
    belongs_to :characters
end