开发者

Best way to utilize rails activerecord abstractions for this query?

So, I have the following sql query that I'm using to pull some relevant information from a database. I want to utilize activerecord abstractions to optimize this query for 开发者_运维百科a rails app. What is the best way to do this?

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; 


i guss you models like this

class Subscription < ActiveRecord::Base
  belongs_to :app
end

class App < ActiveRecord::Base
  has_many :subscriptions
end

you can alter apps add a column named subscriptions_count to use acitverecord's counter_cache feature,then modify your model like this:

class App < ActiveRecord::Base
  has_many :subscriptions,:counter_cache => subscriptions_count
end

and you can query apps:

App.find(:all, :order => "subscriptions_count DESC")
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜