我有以下型号:
class FavoriteDirectorSet < ActiveRecord::Base
has_many :links
has_many :directors, through: :links
end
class Link < ActiveRecord::Base
belongs_to :favorite_director_set
belongs_to :director
end
class Director < ActiveRecord::Base
has_many :links
has_many :favorite_director_sets, through: :links
has_many :movies
end
class Movie < ActiveRecord::Base
belongs_to :director
end
我一直在通过将范围链接在一起来构建查询,但我不清楚如何分解这个。如何创建与给定的 FavoriteDirectorSet id 匹配的电影的 Active Record Relation 对象?
更新
我有两个有效的解决方案(“favourite_director”缩写为 fd):
1)@rubyman 选项 1:
fd_sets = FDSet.find(:fd_set_id)
res = Movie.where('director_id IN (?)', fd_sets.directors.map(&:id))
2)@rubyman 选项 2:
res = Movie.joins(:director=>[:links=>:fd_set]).
where("fd_sets.id = ?", :fd_set_id)