I’m trying to convert a string to a time using DateTime.parse in a scope however, I’m getting an undefined local variable error.
Is it possible to convert a field within a scope or do I need to try something else?
My scope:
scope :time_range, lambda {
a = DateTime.parse(start_time_am)
where("#{a} <= ?", Time.now.strftime('%H'))
}
— UPDATE —
Having played around with this, I’ve discovered I should probably overwrite the default accessor. I now have the following:
def start_time_am
read_attribute(:start_time_am).strftime("%H%M").to_i
end
In the console, my start_time_am field now looks like:
Promotion.last.start_time_am
=> 430
However, if I wanted to define a new field temporarily so I can still use the initial one.
I can access this in the console but not when searching. Eg.
def start_time_new
read_attribute(:start_time_am).strftime("%H%M").to_i
end
def self.time_range
time = Time.now.strftime('%H%M').to_i
where("start_time_new <= ?", time)
end
Gives a unknown column error. I thought attr_reader would solve but it’s not working.
Thanks
If you rewrite this as an equivalent method definition then it might be easier to figure out.
Where is start_time_am coming from? The method doesn’t have any arguments.