Merge a Rails 3 scope into a class

I have 4 areas of Rails 3 that I would like to simplify:

  scope :age_0, lambda {
    where("available_at IS NULL OR available_at < ?", Date.today + 30.days)
  }
  scope :age_30, lambda {
    where("available_at >= ? AND available_at < ?", Date.today + 30.days, Date.today + 60.days)
  }
  scope :age_60, lambda {
    where("available_at >= ? AND available_at < ?", Date.today + 60.days, Date.today + 90.days)
  }
  scope :age_90, lambda {
    where("available_at >= ?", Date.today + 90.days)
  }

I thought of a class method:

def self.aging(days)

  joins(:profile).where("available_at IS NULL OR available_at < ?", Date.today + 30.days) if days==0
  joins(:profile).where("available_at >= ? AND available_at < ?", Date.today + 30.days, Date.today + 60.days) if days==30
  joins(:profile).where("available_at >= ? AND available_at < ?", Date.today + 60.days, Date.today + 90.days) if days==60
  joins(:profile).where("available_at >= ?", Date.today + 90.days) if days==90

end

But I don’t know what to return to make sure that it will be compatible with the areas of Rails 3.

Is this a good approach? Is there a better way to do this?

** edit ** I updated the logic of the method. The if test does not work as I expect.

+3
source share
2 answers

I need a default action. I added 'joins (: profile)'. There may be a better way, but it worked.

def self.aging(days)

  joins(:profile).where("available_at IS NULL OR available_at < ?", Date.today + 30.days) if days==0
  joins(:profile).where("available_at >= ? AND available_at < ?", Date.today + 30.days, Date.today + 60.days) if days==30
  joins(:profile).where("available_at >= ? AND available_at < ?", Date.today + 60.days, Date.today + 90.days) if days==60
  joins(:profile).where("available_at >= ?", Date.today + 90.days) if days==90
  joins(:profile)

end
+3
source

Pass lambda argument?

scope :available_range, lambda { |start|
    where("available_at >= ? AND available_at < ?", start, end+30.days)
}

. " " : http://archives.edgerails.info/articles/what-s-new-in-edge-rails/2010/02/23/the-skinny-on-scopes-formerly-named-scope/index.html

+6

Source: https://habr.com/ru/post/1774974/


All Articles