加入并选择多列

时间:2012-01-15 21:34:20

标签: ruby-on-rails activerecord ruby-on-rails-3.1 arel

我正在尝试在连接后选择多个列。我没有找到一种方法来使用ActiveRecord,而无需在查询中的引号之间编写SQL(我想避免使用)

探索Arel,我发现我可以使用“project”选择多个列,但是我不确定我是否应该直接使用Arel,或者是否有办法实现与AR的相同。

以下是Arel中的代码:

l = Location.arel_table
r = Region.arel_table

postcode_name_with_region_code = l.where(l[:id].eq(location_id)).join(r).on(l[:region_id].eq(r[:id])).project(l[:postcode_name], r[:code])

运行此查询后,我想返回以下内容: (伪代码

"#{:postcode_name}, #{:code}"
  1. 有没有办法使用AR实现相同的查询?
  2. 如果我坚持使用Arel,我怎样才能从上面的查询返回的SelectManager类中获取值。
  3. 提前致谢,

2 个答案:

答案 0 :(得分:0)

使用AR,无需编写任何SQL并假设您的模型和关联是:

模型/ region.rb

class Region < ActiveRecord::Base
  has_many :locations
end

model / location.rb

class Location < ActiveRecord::Base
  belongs_to :region
end

你当然可以这样做:

postcode_name_with_region_code = Location.where(:id=>location_id).includes(:region).collect{|l| "#{l.postcode_name}, #{l.region.code}"}

这将执行查询,然后使用Ruby格式化您的结果(请注意,它将返回一个数组,因为我假设可能会返回多个记录)。如果您只想要一个数组项,可以使用array.first方法来引用它。

您还可以急切加载关联并根据结果构建字符串:

 my_loc = Location.find(location_id, :include=>:region)

 postcode_name_with_region_code = "#{my_loc.postcode_name}, #{my_loc.region.code}"

答案 1 :(得分:0)

predicate = Location.where(:id=>location_id).includes(:region)
predicate.ast.cores.first.projections.clear
predicate.project(Location.arel_table[:postcode_name], Region.arel_table[:code])
相关问题