- 1 year ago 64
Ruby Question

comparison of date >= but not including self


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

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

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


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


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

Answer Source

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')


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download