AnthonyGalli.com AnthonyGalli.com - 29 days ago 9
Ruby Question

comparison of date >= but not including self

model

def previous_user_challenge_date_started
user.challenges.where('date_started >= ?', date_started).order('date_started ASC').first #date_started is a date, not datetime
end


Some challenges will have the same
date_started
so that's why I want
>=
, but right now it keeps reloading the current
@challenge
over and over again when the
link_to
is clicked.

How can I use
>=
but with an exception for whatever is the
@challenge
, so maybe using
not self
somehow in the model method?

view

<%= link_to '← Previous', challenge_path(@challenge.previous_user_challenge_date_started), class: "prev" %>


controller

@challenge = Challenge.find(params[:id])

Answer

Scopes are really handy for this kind of thing:

class Challenge < ActiveRecord::Base

  belongs_to :user

  # return challenges after a particular date
  scope :on_or_after, ->(date) { where(arel_table[:date_started].gteq(date)) }

  # return all but these challenges
  scope :excluding, ->(id) { where.not(id: id) }

  def previous_user_challenge_date_started
    user.challenges             # get the users challenges
     .excluding(self)           # but not this one
     .on_or_after(date_started) # that are on or after the start date
     .order('date_started ASC')
     .last
  end

end

Also here is the obligatory link to an awesome article about using scopes: Mastering ActiveRecord and AREL

Comments