I have 2 models with a many-to-many relationship (simplified here with books-authors example):
class Book < ActiveRecord::Base
has_and_belongs_to_many :authors
end
class Author < ActiveRecord::Base
has_and_belongs_to_many :books
end
I need to display a list of books, and under each one a list of its authors. Users are able to filter via a certain author.
I'm trying to filter via an author in the following way:
Let's assume there's only one resulting book, and it has 3 authors.
books = Book.find(:all, :include => :authors, :conditions => "authors.id = 5")
When I try to list the different authors of the books retrieved, I get only the author with ID=5.
books.first.authors.size # => 1
books.first.authors.first.id # => 5
I would expect rails to go and retrieve all the different authors associated with the books, either during the find query or as a follow-up query, yet it does not.
How can I solve this problem? Is there something wrong with the associations? the find query?
Thanks.