Home Rails 4+: only select specific columns from an included association
Reply: 0

Rails 4+: only select specific columns from an included association

user1649
1#
user1649 Published in May 20, 2018, 9:58 am

I have a user model that belongs to to an account (pretty standard). On every request, I need to retrieve the current_user but I also want to return the account to reduce DB queries:

# ApplicationController
def current_user
  @current_user ||= User.includes(:account).find_by(auth_token: cookies[:auth_token])
end

def current_account
  @current_account ||= current_user.account
end

This works just fine. However, the account record has a lot of extra text data that I don't always want to return. A more permanent solution would be to move those extra fields to a new table called account_details and have a one-to-one between an account and account_details.

However, I need a shorter-term solution that will provide some optimizations until I can refactor that (perfection is an iterative process!).

I want to return ALL columns from the current_user, but I only want to select a few columns from the current_account.

I tried this and I didn't work:

@current_user ||= User.includes(:account).references(:account).select("users.*, account.id, account.uuid").find_by(auth_token: cookies[:auth_token])

When I look at @current_user.account it still displays all the columns with their values and I only wanted the id, uuid columns.

I couldn't find any clear syntax on using select(...) with includes(:association); is this something that's possible?

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.301339 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO