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

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
Python”.

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

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

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

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

Model BookCategoryRelation
belongs_to :book
belongs_to :category
end

So if you want search book with some conditions will be:
@books = Book.all(:joins => “INNER JOIN book_category_relations ON
books.id= book_category_relations.book_id
INNER JOIN categories ON
book_category_relations.category_id = categories.id”,
:conditions => [“categories.name LIKE ?”,
“%#{your_filter}%”])

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

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

This is assuming that a category has a name attribute and it’s the
attribute
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
books.id = 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
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