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

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

Dan L
1#
Dan L Published in 2018-01-05 19:42:01Z

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?

Arun Mathew Kurian
2#
Arun Mathew Kurian Reply to 2018-01-06 05:37:45Z

You need to add an extra association in your User model.

belongs_to :account_columns, -> { select(:id, :uuid) }, class_name: 'Accoun'

This association should be used in your query.

User.includes(:account_columns)

This is because Rails don't have the facility to pass the options for include query.

Also consider using join instead includes in your query, as it also caters your need.

User.joins(:accounts).select("accounts_ids, accounts.uuid")
You need to login account before you can post.

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

© 2016 Powered by mzan.com design MATCHINFO