Skip to content

Instantly share code, notes, and snippets.

@garyharan
Created December 19, 2022 17:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save garyharan/429cf47bd218db842831707fd6d07e73 to your computer and use it in GitHub Desktop.
Save garyharan/429cf47bd218db842831707fd6d07e73 to your computer and use it in GitHub Desktop.
ActiveRecord order by SQL generated value

If you want to create an extra attribute based on SQL query with ActiveRecord you can use the following:

@games = Game.select("*, ABS(#{@profile.level} - level) AS level_difference")

Then in your Ruby code you can refer to things this way:

@games.first.level_difference # => 16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment