Skip to content

Instantly share code, notes, and snippets.

@sourabh-upadhyay
Last active March 29, 2017 13:04
Show Gist options
  • Save sourabh-upadhyay/db7a3de65a4e57fc9b44c1013349b25c to your computer and use it in GitHub Desktop.
Save sourabh-upadhyay/db7a3de65a4e57fc9b44c1013349b25c to your computer and use it in GitHub Desktop.
Alias attribute with eager loading in rails
#Simple monkey patch would work
module ActiveRecord
Base.send :attr_accessor, :_row_
module Associations
class JoinDependency
JoinBase && class JoinPart
def instantiate_with_row(row, *args)
instantiate_without_row(row, *args).tap { |i| i._row_ = row }
end
alias_method_chain :instantiate, :row
end
end
end
end
#Then you can get a column value from a row:
Post.includes(:comments).select("posts.*, 1 as testval").first._row_['test_val']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment