使用 Rails 的电影站点的正确模型数据结构

发布于 2024-10-11 09:26:48 字数 516 浏览 2 评论 0原文

我需要拯救一群与电影相关的人,而不需要重复。

让我们以电影《无耻混蛋》为例。

昆汀·塔伦蒂诺在这里扮演了很多角色。

  • 导演
  • 作家
  • 演员

这是一个 rspec 测试的示例

Movie.find_by_title("Inglourious Basterds").actors.map(&:name).should include("Quentin Tarantino")
Movie.find_by_title("Inglourious Basterds").writers.map(&:name).should include("Quentin Tarantino")
Movie.find_by_title("Inglourious Basterds").directors.map(&:name).should include("Quentin Tarantino")

我应该如何建立模型之间的关系?

I need to save a bunch of people that a related to a movie without duplication.

Let's take the movie Inglourious Basterds as an example.

Here Quentin Tarantino has a bunch of roles.

  • Director
  • Writer
  • Actor

Here is an example of an rspec test

Movie.find_by_title("Inglourious Basterds").actors.map(&:name).should include("Quentin Tarantino")
Movie.find_by_title("Inglourious Basterds").writers.map(&:name).should include("Quentin Tarantino")
Movie.find_by_title("Inglourious Basterds").directors.map(&:name).should include("Quentin Tarantino")

How should I set up the relations between the models?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

陪你搞怪i 2024-10-18 09:26:48

这是一组相当简单的 Rails 模型。

rails g model movie name:string
rails g model person name:string
rails g model movie_role movie:belongs_to person:belongs_to role:string

对于模型协会:

class Person < ActiveRecord::Base
  has_many :movie_roles
  has_many :movies, :through => :movie_roles
end

class Movie < ActiveRecord::Base
  %w(actor director writer).each do |type|
    base = "#{type}_movie_roles"
    has_many base, :conditions => { :role => type }, :class_name => 'MovieRole'
    has_many type.pluralize, :through => base, :source => :person
  end
end

This is a fairly simple set of models for rails to do.

rails g model movie name:string
rails g model person name:string
rails g model movie_role movie:belongs_to person:belongs_to role:string

And for the model associations:

class Person < ActiveRecord::Base
  has_many :movie_roles
  has_many :movies, :through => :movie_roles
end

class Movie < ActiveRecord::Base
  %w(actor director writer).each do |type|
    base = "#{type}_movie_roles"
    has_many base, :conditions => { :role => type }, :class_name => 'MovieRole'
    has_many type.pluralize, :through => base, :source => :person
  end
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文