ActiveRecord的选择与参数绑定 [英] ActiveRecord Select with Parameter Binding
问题描述
我希望使用ActiveRecord的子查询,像这样:
I want to use a subquery with ActiveRecord like so:
User.select(
'users.*,
(select sum(amount)
from subscriptions
where subscriptions.user_id = user.id
and created_at < ? ) as amt)'
).order('amt')
然而,在倒数第二行,我有我无法弄清楚如何绑定时间
类的参数,如的ActiveRecord :: Base的
的选择
方法不接受多个参数(SQL字符串)。我该怎么办?
However, on the second to last line, I have the problem that I can't figure out how to bind the Time
class parameter, as ActiveRecord::Base
's select
method doesn't accept more than one parameter (the sql string). What do I do?
推荐答案
您可以使用的一个<一个href="http://api.rubyonrails.org/classes/ActiveRecord/Sanitization/ClassMethods.html"><$c$c>ActiveRecord::Sanitization$c$c>类方法的。
You can use one of the ActiveRecord::Sanitization
class methods.
这些混合成的ActiveRecord :: Base的
键,几乎所有受保护,使他们通过在模型中定义一个类的方法最容易被访问:
These are mixed into ActiveRecord::Base
and are almost all protected so they are most easily accessed by defining a class method on your model:
class User < ActiveRecord::Base
def self.select_with_args(sql, args)
query = sanitize_sql_array([sql, args].flatten)
select(query)
end
end
这也是值得寻找其他方式来获取你的数据和他们的表现比较子查询的方法。例如,你可以用一个单独的查询获取订阅数:
It's also worth looking for other ways to fetch your data and comparing their performance to the subquery method. For example, you could fetch the subscription counts with a separate query:
subs_by_user = Subscription.group(:user_id).where('created_at < ?', d).count()
这篇关于ActiveRecord的选择与参数绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!