因此,我有以下 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;
最佳答案
我猜你是这样的模特
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")
关于mysql - 使用 Rails ActiveRecord 抽象进行此查询的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5795453/