Rails:find_by_sql 和虚拟列 [英] Rails: find_by_sql and virtual column

查看:39
本文介绍了Rails:find_by_sql 和虚拟列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想显示一个带有标签的列表以及每个标签的元素数量(在我的示例任务"中).

I want to display a list with tags plus the number of elements (in my example "Tasks") for each tag.

为此,我在标签模型中创建了以下方法:

For this purpose I created the following method in my Tag model:

def self.find_with_count
  find_by_sql 'SELECT
                 Tag.name,
                 COUNT(Tag.name) AS taskcount
               FROM
                 tags AS Tag
                 INNER JOIN tags_tasks tt ON tt.tag_id = Tag.id
                 INNER JOIN tasks t ON tt.task_id = t.id
               WHERE
                 t.finished = 0
                 AND t.deleted = 0
               GROUP BY
                 Tag.name
               ORDER BY
                 Tag.name'
end

该方法返回正确的标签名称,但由于某种原因任务计数不在结果中.结果看起来像

The method returns the correct tag names, but for some reason the taskcounts are not in the result. The result looks like

[#<Tag name: "hello">, #<Tag name: "world">]

由于这种方法似乎不起作用,我想知道 Rails 方法是什么来完成这样的任务.谢谢!

As this approach doesn't seem to work, I'm wondering what the Rails-way is to accomplish such a task. Thanks!

推荐答案

计数就在那里,你只是看不到它,因为 taskcount 不是 Rails 为该类 Task 创建的属性,因为它不是列它可以看到.您必须使用属性调用才能找到它.示例:

The count is there, you just can't see it since taskcount is not an attribute Rails creates for that class Task, because it isn't a column that it can see. You have to use the attributes call to find it. Sample:

class Tag < ActiveRecord::Base
  ...
  def taskcount
    attributes['taskcount']
  end
end

Tag.find_with_count.each do |t|
  puts "#{t.name}: #{t.taskcount}"
end

这篇关于Rails:find_by_sql 和虚拟列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆