includes vs joins

includes: for nested associations

Model associations:

  • a_model has many b_models
  • b_model has many c_models
  • b_model has many d_models
  • d_model has one e_model
AModel.includes(b_models: [{ d_models: :e_model }, :c_models]).find(1)

# Code source: RailsGuides
# [13.1.2 Nested Associations Hash]
# http://guides.rubyonrails.org/active_record_querying.html#eager-loading-associations
Category.includes(articles: [{ comments: :guest }, :tags]).find(1)

Model associations:

NOTE: menu_category was designed not to share with other menus, so the association was defined as above.

  • menu has many menu_categories
  • menu_category has many menu_items
@menu = Menu.includes(menu_categories: :menu_items).find_by_name(menu)

Reference

results matching ""

    No results matching ""