gpt4 book ai didi

ruby-on-rails - rails : How to combine multiple ActiveRecord associations to a single collection

转载 作者:行者123 更新时间:2023-12-03 15:56:07 25 4
gpt4 key购买 nike

我有如下内容:

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返回 ActiveRecord::Associations::CollectionProxy属于该项目的 time_entries。

我想要的是将与特定组关联的所有项目关联的所有 time_entries 列表作为单个集合,而无需执行以下操作:
TimeEntry.where(["project_id IN (?)", @group.projects.map{|p| p.id } ])

PS:使用 Rails 4.0.0 | ruby 2.0.0

最佳答案

根据 subset conditions 上的边缘文档,您可以将数组传递给 where() 的条件散列询问。这将返回 ActiveRecord::Relation , 而不是对象数组:

TimeEntry.where(project_id: @group.projects(&:id))

请注意映射简写的使用(带有与号的部分)。这是返回多个对象上的单个属性数组的替代方法,并且(也许)更具可读性:
@group.projects.map{|p| p.id} == @group.projects(&:id)

关于ruby-on-rails - rails : How to combine multiple ActiveRecord associations to a single collection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19008942/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com