如何在 rails 中加入 1:N tables 而不是多行记录获取一行,其中包含来自加入的 table 的 ID 数组的额外列
How to join 1:N tables in rails and instead of multiple rows for record get one row with extra column containing array of IDs from joined table
我有3个模型
class Mission < ActiveRecord::Base
belongs_to :guild
end
class Guild < ActiveRecord::Base
has_many :missions
has_many :guild_coordinators, :dependent => :destroy
has_many :coordinators, :through=> :guild_coordinators, :class_name => "Associate"
end
class GuildCoordinator < ActiveRecord::Base
belongs_to :guild
belongs_to :coordinator, :class_name => "Associate"
end
如果我这样做
Mission.joins(:guild => :guild_coordinators)
我得到每个公会的行 -> 公会协调员协会
是否可以获取加入公会的任务的唯一记录,并在一列中获取数组中所有协调员的 ID?
编辑:
预期结果是这样的:
#<ActiveRecord::Relation [#<Mission id: 13, fy: 2018, guild_id: 31, name: "test mission", status: 0, coordinators: [1,2,3,5,8]>
我的数据库是postgres
作为输出,我需要 gem ajax-datatables-rails
的 Active Record 关系
对于 Postgresql,您可以使用 array_agg
aggregate function:
Mission.
joins(guild: :guild_coordinators).
select('missions.*, array_agg(guild_coordinators.id) as coordinators').
group(:id)
你得到的恰好是 ActiveRecord::Relation
,它将包含(调用后)Mission
个具有附加字段 coordinators
:Array.
的对象
第二个选项是使用 .includes
就像我或@garrett-motzner 评论显示的那样。
我有3个模型
class Mission < ActiveRecord::Base
belongs_to :guild
end
class Guild < ActiveRecord::Base
has_many :missions
has_many :guild_coordinators, :dependent => :destroy
has_many :coordinators, :through=> :guild_coordinators, :class_name => "Associate"
end
class GuildCoordinator < ActiveRecord::Base
belongs_to :guild
belongs_to :coordinator, :class_name => "Associate"
end
如果我这样做
Mission.joins(:guild => :guild_coordinators)
我得到每个公会的行 -> 公会协调员协会
是否可以获取加入公会的任务的唯一记录,并在一列中获取数组中所有协调员的 ID?
编辑: 预期结果是这样的:
#<ActiveRecord::Relation [#<Mission id: 13, fy: 2018, guild_id: 31, name: "test mission", status: 0, coordinators: [1,2,3,5,8]>
我的数据库是postgres 作为输出,我需要 gem ajax-datatables-rails
的 Active Record 关系对于 Postgresql,您可以使用 array_agg
aggregate function:
Mission.
joins(guild: :guild_coordinators).
select('missions.*, array_agg(guild_coordinators.id) as coordinators').
group(:id)
你得到的恰好是 ActiveRecord::Relation
,它将包含(调用后)Mission
个具有附加字段 coordinators
:Array.
第二个选项是使用 .includes
就像我或@garrett-motzner 评论显示的那样。