3

I have a Rails app and am in the process of refactoring my controllers and looking at all the DB queries made by my application.

Would like to use include/join as much as possible to limit the number of DB queries made and I'm using devise for authentication.

Here's the problem I'm having:

Currently, let's say that the current user (as determined by Devise) has many Services and has many Friends. If, I want to display the user, services, and friends, I can do something like this in my controller:

def show
  @friends = @current_user.friends
  @services = @current_user.services
end

Now the problem here is that I will have made three individual SQL queries. One to grab the current user (which Devise handles), another to get the friends and a third one to get the services.

Instead (if it weren't for Devise handling the SQL query on the user), I could use the include method to do something like:

current_user = User.where(<devise's method to find the user>).include(:services).include(:friends)

To get the exact object that I need for each controller endpoint with only one query to the database.

Any ideas on how to do this? Do I have to start modifying Devise's current_user method or is there a better way to do this?

Karim
  • 1,303
  • 1
  • 14
  • 23
  • Looks like this has been [discussed on GitHub](https://github.com/plataformatec/devise/issues/938). – Sam Coles Jul 22 '16 at 20:18
  • I believe this responds your question http://stackoverflow.com/questions/6902531/how-to-eager-load-associations-with-the-current-user – neydroid Jul 22 '16 at 21:17
  • @neydroid no it doesn't - it just shows you how to eager load a table on ALL requests. This is quite useless and actually hurts performance as you don't want every associated table on every request. In any application, current_user will probably have a large number of associations and each controller probably only needs 1 or 2 of them. The query in the DB to current_user needs to be deferred till the request actually hits the controller method. – Karim Jul 24 '16 at 00:32
  • @SamColes the GitHub issue talks more about eager loading the relationship ONCE current_user has already been loaded. Essentially, I think there should be a way to cut down the number of queries from 3 to 1...not from a large number, as indicated in the Github post due to some nesting on the association, to 3. – Karim Jul 24 '16 at 00:41

0 Answers0