Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to be explicit on .select() columns when using .includes() in Rails?

I am trying to optimize my query for RAM usage and a table that is in the .includes(:ocr) has too many columns on it (and also a large-sized column). Is there a way that I can still utilize Rails' .includes() but pick out explicit .select() columns from the includes() tables?

I want to exclude using an N+1 which is what a .joins() generates.

ie.

User.select(:email).includes(:ocr => select(:small_value_only))
like image 402
Kamilski81 Avatar asked Nov 19 '18 19:11

Kamilski81


1 Answers

You don't give much information on how your tables are set, so I'll assume that User belongs_to :ocr, User has an ocr_id column, and the ocr table's name is ocr.

You should use joins instead of includes, that's how you generate an INNER JOIN query and be able to retrieve the joined table's column(s). Finally you can alias the column name with AS, so it's easier to retrieve in your model:

users = User.joins(:ocr).select(:email, :ocr_id, '`ocr`.`small_value_only` AS `ocr_sma`')

users.each do |user|
  user.email # Users.email for this record
  user.ocr_sma # Joined Ocr.small_value_only for this record
end

(Obviously I aliased it ocr_sma, but you can give it the name you want)

like image 103
Benj Avatar answered Nov 03 '22 00:11

Benj