Forum: Ruby on Rails Selecting conditionally from HABTM

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Daniel H. (Guest)
on 2006-01-02 07:46
(Received via mailing list)
I was wondering whether there is a nice Rubyesque way of selecting
from a pair of HABTM models where one of them is inherited from
another object.

Here is the situation:

I have a 'posts' table from which 'replies' and 'articles' are
inherited. Articles have_and_belong_to_many categories, but neither
posts nor replies do (it just does not seem to be very useful). I want
to have a page which shows (paginatedly) the articles in a selected
category. So given a category, I would like to return an array of all
of the articles associated with it.

I am no master of SQL syntax, so I am not sure what to include in a
'LEFT JOIN" statement.

Thanks for any help,

Daniel H.
Derek H. (Guest)
on 2006-01-02 12:03
(Received via mailing list)

Maybe I'm not understanding the problem correctly, but if you are
using single-table inheritance (ie a 'posts' table with a 'type'
column that would either be 'Post', 'Reply', or 'Article') you can
grab the articles associated with a selected category simply through:


In other words, you can refer directly to the Article class.

- Derek

On 1/2/06, Daniel H. <removed_email_address@domain.invalid> wrote:
> to have a page which shows (paginatedly) the articles in a selected
> Rails mailing list
> removed_email_address@domain.invalid

Derek H.
HighGroove Studios -
Atlanta, GA
Keeping it Simple.
Daniel H. (Guest)
on 2006-01-02 20:46
(Received via mailing list)
That will give me the correct articles array, but how would I pass
that to a paginator? I have looked through the API docs and have not
been able to find any way to tell the paginator to operate just on a
certain array and not all Articles? It seems like there should just be
a :collection option to take an array and paginate that.

Any help is appreciated.

Daniel H.
David R. (Guest)
on 2006-01-02 23:57
(Received via mailing list)

How about:

@article_pages, @articles = paginate :articles, :per_page =>
10, :conditions => 'category = category_name'

The :conditions option gets passed on to Article.find(), effectively
letting you specify the WHERE clause of the query it uses to get the
Articles for display. Not exactly the 'paginate-an-arbitrary-array'
you're looking for, I know, but if I understand what you're trying to
do, this should be an option for you.

Does that help?

This topic is locked and can not be replied to.