Selecting conditionally from HABTM

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.


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. [email protected] wrote:

to have a page which shows (paginatedly) the articles in a selected
Rails mailing list
[email protected]

Derek H.
HighGroove Studios -
Atlanta, GA
Keeping it Simple.

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.


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 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