Search code examples
ruby-on-rails-3model-associations

Does rails load associated relation each time


E.g. I have a model called Book which belongs_to model Shelf with fields :bookcase and :number.

I wonder, if I call to book.shelf.bookcase and then later to book.shelf.number does Rails actually load corresponding shelf each time? Or does it cache book.shelf somewhere? Shouldn't I make a new variable shelf = book.shelf and use shelf.bookcase and shelf.number instead?


Solution

  • Rails will cache association information, so you get whatever is in the cache when you access it. It does not reload it from the database each time.

    There are cases when you do want a reload from the database, in which case the following syntax is used:

    book.shelf(true).number
    

    See section 3.1 in A Guide to Active Record Associations.