Rails 3
I have a relationship where Category has_and_belongs_to_many Article. I
want to grab a small subsection of articles related to a particular
category. When I try to iterate over these, Rails tries to count the
records and gets the wrong number.
The issue is that there is bug in the way ActiveRecord counts records in
associations.
For example:
c = Category.first
c.articles.count
Outputs 8 which is correct.
c.articles.limit(3).count
Also outputs 8, when it should be 3
The problem is that the SQL ActiveRecord generates, just appends the
limit to end of the SQL string:
SELECT COUNT(*) AS count_id FROM articles INNER JOIN
articles_categories ON articles.id =
articles_categories.article_id WHERE
(articles_categories.category_id = 9 ) LIMIT 3
All the limit statement does here is limit the number of output lines:
which is always 1.
If ActiveRecord generated this, it would work:
SELECT count(*) FROM (
SELECT *
FROM articles
INNER JOIN articles_categories ON articles.id =
articles_categories.article_id
WHERE (articles_categories.category_id = 9 )
LIMIT 6, 4) inner_table
To correct this I think I’d need to override
ActiveRecord::Calculations#count. Is there a better way?
If this was just a has_many relationship I could use:
Article.where([“category_id = ?”, c.id]).limit(3).count
but that won’t work with a has_and_belongs_to_many because articles
doesn’t have a category_id field