如何在使用`平均()`使用`to

编程入门 行业动态 更新时间:2024-10-27 23:19:30
本文介绍了如何在使用`平均()`使用`to_sql`在AREL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想从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"

更多推荐

如何在使用`平均()`使用`to

本文发布于:2023-10-26 07:27:51,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1529479.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:平均   如何在

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!