mysql - 使用 Rails ActiveRecord 抽象进行此查询的最佳方法是什么?

标签 mysql ruby-on-rails activerecord

因此,我有以下 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/

相关文章:

mysql - 尝试远程访问mysql

mysql - Spring Security - 查询security-context.xml中的变化

php - Zend Date MySQL 时区偏移问题

ruby-on-rails - 使用 Ransack 搜索值数组

mysql - 如何在 MySQL 8(如 MSSQL)上使用表达式作为 LAG() 第二个参数?

javascript - 获取 View 中表单内选定的下拉值

javascript - 如何使用 json 数组填充 Rails 下拉菜单

ruby-on-rails - ruby rails : updated_at - set as 0 on creation

sql-server - 使用 ActiveRecord 连接到 SQL Server

mysql - 数据库 :seed not loading models