Question

I would like to ask, what is a proper way to select books from given shelf

class Book < ActiveRecord::Base
    belongs_to :shelf
end

class Shelf < ActiveRecord::Base
    has_many :books
end

Using Book.where(:shelf => shelf) raises exception like no such column: book.shelf. I know I can reverse it, like shelf.books but this won't work if there is need to filter by more than one object. All I could find is that query should looks like Books.where(:shelf_id => shelf.id) but this doesn't seem very DRY or even a bit cool..

Was it helpful?

Solution

You can use joins or includes :

Book.joins(:shelfs) # will load all the Books that have one Shelf

Book.includes(:shelfs) # will load all the Books and Shelfs even if the book has no Shelf associated

# or beginning with a Shelf object:
@shelf.books # will return all Book where shelf_id = @shelf.id

If you need precisions / have questions, don't hesitate to comment ;) (I'm thinking of you phrase "like shelf.books but this won't work if there is need to filter by more than one object." which I don't really understand)

OTHER TIPS

For relational dryness, have a peek at delegation, where references from one model to another are encapsulated within one of the models. There's quite some discussion on whether or not this is a solution to a real problem, I personally believe it can be, but decide for yourself. The article is old but not outdated.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top