【问题标题】:Best way to utilize rails activerecord abstractions for this query?对此查询使用 rails activerecord 抽象的最佳方法是什么?
【发布时间】:2023-03-09 00:37:01
【问题描述】:

因此,我使用以下 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; 

【问题讨论】:

    标签: mysql ruby-on-rails activerecord


    【解决方案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")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-26
      • 1970-01-01
      • 2011-01-24
      • 2017-11-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多