Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 672
lulalala Avatar asked Dec 05 '25 11:12

lulalala


1 Answers

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
like image 148
Mischa Avatar answered Dec 07 '25 15:12

Mischa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!