我有類似如下:Rails的:如何將多個ActiveRecord關聯結合單個集合
class Group < ActiveRecord::Base
has_many :group_projects, dependent: :destroy
has_many :projects, through: :group_projects
end
class Projects < ActiveRecord::Base
has_many :group_projects, dependent: :destroy
has_many :groups, through: :group_projects
has_many :time_entries
end
class TimeEntry < ActiveRecord::Base
belongs_to :project
end
所以,project.time_entries
返回屬於該項目time_entries的ActiveRecord::Associations::CollectionProxy
。
我要的是有關與特定組作爲一個集合相關聯的所有項目的所有time_entries的列表,而不必像做:
TimeEntry.where(["project_id IN (?)", @group.projects.map{|p| p.id } ])
PS:使用Rails 4.0.0 | ruby 2.0.0
傳遞映射項目到您的查詢有什麼問題?我懷疑有沒有內置的幫手來幫助完成這件事。 – zeantsoi
@zeantsoi試過這樣做: time_entries = group.projects.map {| p | p.time_entries} 我可以把它變成一個單一的數組,但就是這樣 - 一個數組 - 所以我可以使用它的任何ActiveRecord方法(例如:.where等)。我所追求的是所有可以應用ActiveRecord方法的time_entries的ActiveRecord關係/集合 – olvado
瞭解。請參閱下面的答案。 – zeantsoi