views:

32

answers:

1

Here's my query for the curious. Only the first and last lines should bear on this question:

SELECT s.parent_id AS id, COUNT(s.parent_id) as count
  FROM items i
  LEFT OUTER JOIN (SELECT item_id, user_id, MAX(created_at) as created_at
    FROM item_views iv
    WHERE iv.user_id = ?
    GROUP BY item_id) AS v ON i.id = v.item_id
  LEFT OUTER JOIN categories c ON c.id = i.category_id
  INNER JOIN (SELECT node.id AS node_id, parent.title AS parent_title, parent.id AS parent_id
    FROM categories AS node, categories AS parent
    WHERE node.lft BETWEEN parent.lft AND parent.rgt) s ON s.node_id=i.category_id
  WHERE (i.updated_at > v.created_at OR v.created_at IS NULL)
  AND i.updated_at > ?
  GROUP BY s.parent_id;

When I call this using find_by_sql, the values under the count column seem to be strings like "1" instead of integers. Of course, I can call to_i easily, but surely that's not the best solution. I suspect there might be something wrong with my query that's causing a string to be returned by MySQL.

+1  A: 

You need to cast your returned count attribute as an integer.

find_by_sql returns an array of attributes from your query, Rails treats those attributes as strings, and since count is an attribute of your query array, it is a string in the return. Take a look at the documentation for the method for confirmation of this:

http://apidock.com/rails/ActiveRecord/Base/find_by_sql/class

Jed Schneider