所以,我有以下sql查询,我用它从数据库中提取一些相关信息。我想利用activerecord抽象来优化rails应用程序的查询。这样做的最佳方式是什么?
select count(s.app_id) counters , app.name, app.app_id from subscriptions s, apps app where s.app_id = app.id group by s.app_id order by counters;
答案 0 :(得分:1)
我像你这样的模特
class Subscription < ActiveRecord::Base
belongs_to :app
end
class App < ActiveRecord::Base
has_many :subscriptions
end
你可以改变应用程序添加名为subscriptions_count的列以使用acitverecord的counter_cache功能,然后像这样修改你的模型:
class App < ActiveRecord::Base
has_many :subscriptions,:counter_cache => subscriptions_count
end
您可以查询应用:
App.find(:all, :order => "subscriptions_count DESC")