gpt4 book ai didi

ruby-on-rails - Arel::SelectManager 如何访问包括投影在内的结果

转载 作者:行者123 更新时间:2023-12-04 17:39:55 30 4
gpt4 key购买 nike

我正在尝试访问连接的结果,其中两个表的列都被指定为投影的一部分。

我有 2 个模型(Rails 4.2.11;Arel 6.0.4;Ruby 2.5.3)

# Table name: users
#
# id :integer not null, primary key
# name :string(255)
# email :string(255)
# created_at :datetime not null
# updated_at :datetime not null

class User < ActiveRecord::Base
has_many :photos
end

# Table name: photos
#
# id :integer not null, primary key
# name :string(255)
# created_by_id :integer
# assigned_id :integer
# created_at :datetime not null
# updated_at :datetime not null
# user_id :integer

class Photo < ActiveRecord::Base
belongs_to :user
end
creators = User.arel_table.alias('creators')
updaters = User.arel_table.alias('updaters')
photos = Photo.arel_table

photos_with_credits = photos.
join(photos.join(creators, Arel::Nodes::OuterJoin).on(photos[:created_by_id].eq(creators[:id]))).
join(photos.join(updaters, Arel::Nodes::OuterJoin).on(photos[:assigned_id].eq(updaters[:id]))).
project(photos[:name], photos[:created_at], creators[:name].as('creator'), updaters[:name].as('editor'))
# generated SQL
SELECT photos.name, photos.created_at, creators.name AS creator, updaters.name AS editor
FROM photos
INNER JOIN (SELECT FROM photos LEFT OUTER JOIN users creators ON photos.created_by_id = creators.id)
INNER JOIN (SELECT FROM photos LEFT OUTER JOIN users updaters ON photos.updated_by_id = updaters.id)

我想如何处理结果

photos_with_credits.map{|x| "#{photo.name} - copyright #{photo.created_at.year} #{photo.creator}, edited by #{photo.editor}"}.join('; ')

这可能是一个非常愚蠢的问题,但是......由于 map 已从 SelectManager 类中弃用(并删除),因此我无法找到使用 SelectManager 结果生成有意义输出的方法。

非常感谢您的帮助。

最佳答案

简化了 activerecord/arel 查询构建器

修改后的代码

photos_with_credits = Photo.select([photos[:name], photos[:created_at], creators[:name].as('creator'), updaters[:name].as('editor')]).
joins(photos.outer_join(creators).on(photos[:created_by_id].eq(creators[:id])).join_sources).
joins(photos.outer_join(updaters).on(photos[:assigned_id].eq(updaters[:id])).join_sources)

photos_with_credits.map do |photo|
puts "#{photo.name} - copyright #{photo.created_at.year} #{photo.creator}, edited by #{photo.editor}".light_blue
end
修改后的 SQL(更简单)
SELECT photos.name, photos.created_at, creators.name AS creator, updaters.name AS editor 
FROM photos
LEFT OUTER JOIN users creators ON photos.created_by_id = creators.id
LEFT OUTER JOIN users updaters ON photos.assigned_id = updaters.id

关于ruby-on-rails - Arel::SelectManager 如何访问包括投影在内的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54976562/

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