Search HABTM relationship in ActiveRecord

Consider the following scenario:

Book has_and_belong_to_many Category.
In other words, a category may have a lot of books, and a book can
have more than one category.

What is the best practice to query all books related to some specified

For example, if I have following books
“From Java To Ruby” - Category: Java, Ruby
“Ruby P.ming” - Category: Ruby
“Inside Python” - Category: Python

If I search Java & Python, I got “From Java To Ruby” and “Inside

My goal is use a single query join to fetch the results.
It’s possible to use find_by_sql, but I wonder if is there any better

I think the best way to implement HABTM is using midle model, it will
for your query performance

Model Book
has_many :book_category_relations
has_many :categories, :through => :book_category_relation

Model Category
has_many :book_category_relations
has_many :books, :through => :book_category_relations

Model BookCategoryRelation
belongs_to :book
belongs_to :category

So if you want search book with some conditions will be:
@books = Book.all(:joins => “INNER JOIN book_category_relations ON book_category_relations.book_id
INNER JOIN categories ON
book_category_relations.category_id =”,
:conditions => [“ LIKE ?”,

Most of the time, I don’t use habtm because I want complete control on
middle model.
So if you’re following Hendra’s models, to search for a book under a

cat = [‘Java’, ‘Python’]
books = Book.where(:categories => {:name =>

This is assuming that a category has a name attribute and it’s the
you use for the category name. haha! that’s confusing.
good luck!

On Tue, Feb 8, 2011 at 12:22 PM, Hendra G.
[email protected]wrote:

has_many :book_category_relations = book_category_relations.book_id

“Inside Python” - Category: Python
“Ruby on Rails: Talk” group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at

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