Trivial SQL query - how to do it with ActiveRecord?


I've been trying to read ActiveRecord tutorials etc. but haven't figured out how to get the information I want. Let's say I have a users who own one to many bookshelves and some of these bookshelves contain books. Now I would like to get a list of books that belong to user named Timeon:

SELECT FROM books, shelves, users WHERE AND AND'Timeon';

The models would be something like this (from the top of my head, may not be correct):

Class User < ActiveRecord::Base   has_many :book_shelves end

Class BookShelve < ActiveRecord::Base   belongs_to :user   has_many :books end

Class Book < ActiveRecord::Base   belongs_to :book_shelves end

So, how to get a list of Book objects that belong to user named Timeon with a single line of code? Most examples I've seen first find the user, then they list the shelves etc. but I would expect something this trivial to be simple to achieve with a single call.

A classic HABTM!

Class User < ActiveRecord::Base has_many :books, :through => :book_shelves


Class BookShelve < ActiveRecord::Base belongs_to :user has_many :books end

Class Book < ActiveRecord::Base belongs_to :user, :through => :book_shelves end

You can get the list of books like so:

Book.where( :user => { :name => ? }, params[:username] )

refer these for more: