2

I started using class method scopes because I need to pass some argument into the scope. Taking the Rails Guide example:

  def self.1_week_before(time)
    where("created_at < ?", time)
  end

However in my site sometimes the argument can be nil, in that case I want to bypass that scoping and go to the next scope in the chain.

I added the if condition in the method:

  def self.1_week_before(time)
    if time
      where("created_at < ?", time)
    end
  end

However when I use this method in the middle of scope chaining, it will gives undefined method for nil:NilClass error. How can I fix this?

lulalala
  • 17,572
  • 15
  • 110
  • 169

1 Answers1

4

This returns nil, so you get the error when you chain:

def self.1_week_before(time)
  if time
    where("created_at < ?", time)
  end
end

To prevent this you could return scoped:

def self.1_week_before(time)
  if time
    where("created_at < ?", time)
  else
    scoped
  end
end
Mischa
  • 42,876
  • 8
  • 99
  • 111
  • 1
    I just found here (http://stackoverflow.com/questions/3735838/empty-scope-with-ruby-on-rails) that `scoped` should be better than `all`. Can you change it and I'll accept it. – lulalala Mar 09 '12 at 04:25
  • Thanks for pointing that out... I learned something myself :-) – Mischa Mar 09 '12 at 04:31