Counting items in associate with a limit

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

I think I’ve found a workaround.

category.articles.limit(3).count

=> 8

category.articles.find(:all, :limit => “3”).count

=> 3

If I use the old Rails 2 methods, the system works correctly.

hmm… what happens if you use category.articles.limit(3).all.count

On Mon, Feb 14, 2011 at 4:37 PM, Rob N. [email protected]
wrote:

If I use the old Rails 2 methods, the system works correctly.
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs