Rails One-to-Many Query Question
I feel like I'm missing something obvious here, so hopefully someone can help me out.
Lets say I have 3 models: Buildings, Shelves, and Books.
The problem I am trying to solve is to remove all the shelves which have no books out of a particular group of buildings.
The basic structure would look like this:
class Building
has_many :shelve开发者_如何学JAVAs
end
class Shelf
has_many :books
belongs_to :building
end
class Book
belongs_to :shelf
end
I don't need this to be extremely efficient, but I do want to keep it from being horribly inefficient. More specifically, If I have a building whose empty shelves need to be deleted, Here is what I've been trying to do to find the shelves which are empty:
Shelf.joins(:books).where("books.id is NULL").where(:building_id => building_id)<other_conditions...>
However, this query isn't giving me the results I expect (its not returning any shelves when I know some are empty). I was hoping that the join would fill in NULL for the books.id column for a shelf with no books, but it appears I am mistaken.
Is there another way to accomplish this, or is there something simple that I'm missing? Thanks for the help!
Try the same query with includes
instead of joins
.
books.id
can never be NULL
, because you asked for the books which belong to shelves. joins
will only give you the records for which the association is set, so you're asking for the books whose ids are both NULL
and NOT NULL
.
This answer might shed some light on the differences between the two methods.
精彩评论