如何在使用`平均()`使用`to_sql`在AREL?平均、如何在、AREL、to_sql

2023-09-08 15:54:27 作者:For丨丶Tomorrow

我想从AREL的get SQL,但它不能在正常工作情况下,我用平均(:星)

I am trying to the get SQL from AREL, but it does not work in case I use average(:stars) :

本作品:

Review.where("reviewed_user_id = ?", self.reviewed_user_id).to_sql
#=> "SELECT `reviews`.* FROM `reviews` WHERE (reviewed_user_id = 3)"

这使得 NoMethodError

Review.where("reviewed_user_id = ?", self.reviewed_user_id).average(:stars).to_sql
#=> undefined method `to_sql' for 3:Fixnum

所以这意味着 to_sql 是越来越呼吁AREL的结果,而不是AREL对象 - 但为什么

So that means that to_sql is getting called on the result of the AREL instead of on the AREL object - but why?

如何生成的SQL?

推荐答案

这是发生的原因是因为一般的方法是在的ActiveRecord ::关联,不阿雷尔,这迫使计算。

The reason this is happening is because the average method is on ActiveRecord::Relation, not Arel, which forces the computation.

m = Review.where('id = ?', 42).method(:average)
#=> #<Method: ActiveRecord::Relation(ActiveRecord::Calculations)#average>
m.source_location  # or m.__file__ if you're on a different version of Ruby
#=> ["/Users/jtran/.rvm/gems/ruby-1.9.2-p0/gems/activerecord-3.0.4/lib/active_record/relation/calculations.rb", 65]

通过检查的ActiveRecord ::计算的内部,你可以从中获得如何得到它使用SQL。

By checking out the internals of ActiveRecord::Calculations, you can derive how to get at the SQL that it uses.

my_reviewed_user_id = 42
relation = Review.where('reviewed_user_id = ?', my_reviewed_user_id)
column = Arel::Attribute.new(Review.unscoped.table, :stars)
relation.select_values = [column.average]
relation.to_sql
#=> "SELECT AVG(\"reviews\".\"stars\") AS avg_id FROM \"reviews\" WHERE (reviewed_user_id = 42)"

小心,如果你在控制台上工作。 ActiveRecord的::关系 缓存一些东西,所以如果你键入上述成一行控制台线路,它实际上行不通,因为pretty的印刷势力的关系。分离上述用分号,也没有新的生产线,但是,将正常工作。

Careful if you're working at the console. ActiveRecord::Relation caches things so if you type the above into the console line by line, it will actually not work, because pretty-printing forces the relation. Separating the above by semicolons and no new lines, however, will work.

另外,你可以直接使用阿雷尔,像这样:

Alternatively, you can use Arel directly, like so:

my_reviewed_user_id = 42
reviews = Arel::Table.new(:reviews)
reviews.where(reviews[:reviewed_user_id].eq(my_reviewed_user_id)).project(reviews[:stars].average).to_sql
#=> "SELECT AVG(\"reviews\".\"stars\") AS avg_id FROM \"reviews\" WHERE \"users\".\"reviewed_user_id\" = 42"
 
精彩推荐
图片推荐