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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With