SELECT ... AS ... 使用 ActiveRecord

use*_*058 5 ruby-on-rails

是否可以使用 rails 进行这样的查询?

SELECT items.*, (select count(*) from ads where item_id = items.id) as adscount WHERE 1
Run Code Online (Sandbox Code Playgroud)

然后像这样访问这个字段?

@item.adscount 
Run Code Online (Sandbox Code Playgroud)

例如,每个项目都有一百个左右的广告。在项目索引视图中,我需要显示每个项目有多少个广告。

目前我只知道如何对每个项目进行唯一查询,例如:

select count(*) from ads where item_id = 1
select count(*) from ads where item_id = 2
select count(*) from ads where item_id = 3
etc
Run Code Online (Sandbox Code Playgroud)

编辑:

做了一个计数器缓存列。

这给了我巨大的性能提升。

小智 0

使用 Rails Counter Cache http://railscasts.com/episodes/23-counter-cache-column

然后您就可以像这样使用它@item.ads.count,并且这不会产生任何数据库查询。另外(如果你真的想按照你的方式使用它)你可以创建一个模型方法

def adscount
  self.ads.count
end
Run Code Online (Sandbox Code Playgroud)