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))
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With