我有一个有许多剧集的节目,剧集中有许多人通过贡献。 (见下图)
我已将has_many :people, through: :contributions
添加到Show
,因此我可以:game_of_thrones.people.count
,甚至:
has_many :actors, -> { joins(:roles).merge(Role.actors).distinct },
through: :contributions, source: :person
-
game_of_thrones.actors.count
但我想做的是在game_of_thrones或breaking_bad等上创建一个演员列表,按演出次数排序。
示例:
我的问题是两个人。
如何根据贡献计数返回节目中的顶级演员列表?
我应该通过ActiveRecord还是SQL查询来执行此操作。什么是更好地理解这一点的好参考,所以我可以停止打扰堆栈溢出?
class Show < ActiveRecord::Base
has_many :episodes, inverse_of: :show
has_many :contributions, through: :episodes
has_many :people, through: :contributions
has_many :actors, -> { joins(:roles).merge(Role.actors) },
through: :contributions, source: :person
end
class Episode < ActiveRecord::Base
belongs_to :show, inverse_of: :episodes
has_many :contributions, inverse_of: :episode
has_many :roles, through: :contributions
has_many :people, through: :contributions
end
class Contribution < ActiveRecord::Base
belongs_to :episode, inverse_of: :contributions
belongs_to :person, inverse_of: :contributions
belongs_to :role, inverse_of: :contributions
end
class Person < ActiveRecord::Base
has_many :contributions, inverse_of: :person
has_many :episodes, through: :contributions
has_many :roles, through: :contributions
scope :actors, -> { joins(:roles).merge(Role.actors) }
end
class Role < ActiveRecord::Base
has_many :contributions, inverse_of: :role
has_many :people, through: :contributions
has_many :episodes, through: :contributions
scope :actors, -> { where(name: 'Actor') }
end
查询失败:game_of_thrones.people.joins(:contributions).distinct.joins(:episodes).where("episodes.show_id = 1").order("count(episodes.show_id) desc")
game_of_thrones.guests.joins(:contributions).order("count(contribuions.id) desc")