Trivial SQL query - how to do it with ActiveRecord?

Hi,

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 books.name FROM books, shelves, users WHERE
books.shelve_id=shelves.id AND shelves.owner_id=users.id AND
users.name=‘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
end

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:

Hi,

On Aug 18, 7:08 pm, Dheeraj K. [email protected] wrote:

A classic HABTM!

Yes indeed - and Thank You! Solved the problem. I got confused by the
picture on the association basics -section: I thought Appointment was
the high level item “owning” Patients and Physicians, like what one
would draw in an UML diagram.