Skip to content

Instantly share code, notes, and snippets.

@yasaichi
Created April 19, 2015 13:30
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 yasaichi/5026e3c96392ec6a26be to your computer and use it in GitHub Desktop.
Save yasaichi/5026e3c96392ec6a26be to your computer and use it in GitHub Desktop.
Instance methods for ActiveRecord to fetch the "neighbor" records
module NeighborRecords
def previous_one(col_name = :id)
condition = self.class.arel_table[col_name].lt(public_send(col_name))
self.class.where(condition).order(col_name => :desc).first
end
def next_one(col_name = :id)
condition = self.class.arel_table[col_name].gt(public_send(col_name))
self.class.where(condition).order(col_name => :asc).first
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment