lulalala
lulalala

Reputation: 17981

Rails: how to make class method scope to handle nil arguments

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?

Upvotes: 3

Views: 1279

Answers (1)

Mischa
Mischa

Reputation: 43298

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

Upvotes: 4

Related Questions