【问题标题】:Retrieving multiple records through has_many association通过 has_many 关联检索多条记录
【发布时间】:2014-03-12 03:32:09
【问题描述】:

我正在开发一个 Ruby on Rails 4 应用程序,它允许用户检查他们看过的电影。我有一个页面显示通过Film 模型捕获的电影列表。另外,我有一个 Nomination 模型,它可以捕获每个奥斯卡提名,还有 PersonSong 模型,它们也可以获得提名并属于 Film

在列出电影的页面上,我还想显示电影被提名的所有类别。我知道我可以通过 @film.nominations 轻松访问所有电影提名,因为我创建了这个 has_many 关联,但这并没有捕获属于该特定电影的任何人或歌曲提名。

有没有办法显示给定电影的所有提名,无论提名是针对电影、人物还是歌曲?

以下是我目前拥有的模型:

class Category < ActiveRecord::Base
  # DB columns: name, display_order

  has_many :nominations
end


class Nomination < ActiveRecord::Base
  # DB columns: category_id, nominee_id, nominee_type

  belongs_to :category
  belongs_to :nominee, polymorphic: true

  validates :category, presence: true
  validates :nominee, presence: true
end


class Film < ActiveRecord::Base
  # DB columns: name, image_url
  has_many :nominations, as: :nominee
  has_many :film_views
  has_many :people
  has_many :songs
end


class Person < ActiveRecord::Base
  # DB columns: name, film_id
  belongs_to :film
  has_many :nominations, as: :nominee
end


class Song < ActiveRecord::Base
  # DB columns: name, film_id
  belongs_to :film
  has_many :nominations, as: :nominee
end

【问题讨论】:

  • 是电影和电影是两个不同的模型
  • 不,它们是同一型号。我只是互换使用这些术语。

标签: ruby-on-rails postgresql activerecord


【解决方案1】:

因为在所有情况下,任何人或歌曲的提名都与电影有关。 提名应该有电影ID是有道理的;有了这个你的问题已经解决了。注意一个主要原因是因为一个人应该属于一个或多个电影。

无论如何 如果您想获得一部电影的所有提名,您可以使用此代码

def all_nominations
  Nominations.where(nominee_type: 'Person', nominee_id: self.people.map(&:id)).or(nominee_type: 'Song', nominee_id: self.songs.map(&:id)).or(nominee_type: 'Film', nominee_id: self.id)
end

【讨论】:

  • 您的解决方案对我有用,稍作修改:self.nominations + Nomination.where(nominee_type: 'Person', nominee_id: self.people.map(&:id)) + Nomination.where (nominee_type: '歌曲', nominee_id: self.songs.map(&:id))
猜你喜欢
  • 2012-10-24
  • 2015-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多