Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails ActiveRecord Includes with Inner Join

When using includes on an ActiveRecord model, is there a better way to specify an inner join then:

User.includes(:address).joins(:address)

It seems like there should be a more beautiful way to specify when you want an inner join and an includes?

like image 735
Tom Rossi Avatar asked Dec 06 '16 20:12

Tom Rossi


People also ask

What is the difference between includes and joins?

What is the difference between includes and joins? The most important concept to understand when using includes and joins is they both have their optimal use cases. Includes uses eager loading whereas joins uses lazy loading, both of which are powerful but can easily be abused to reduce or overkill performance.

What is ActiveRecord in Ruby on Rails?

1 What is Active Record? Active Record is the M in MVC - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.

What does ActiveRecord base do?

ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending. Edit: as Mike points out, in this case ActiveRecord is a module...

Is ActiveRecord an ORM?

ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code.


1 Answers

As Tom Rossi explained in the comment section of your question.

  • If you want to join the address table with inner join association you should use join()
  • If you want to preload the data you should use include() or eager_load(). I Personally prefer eager_load() function, because it guaranties that left join is going to be use. includes() may decide to use separate queries instead of left join association
  • If you want to use inner join and preload the data you just combine the two approaches as it is in you case
like image 198
Yuliyan Avatar answered Sep 21 '22 21:09

Yuliyan