Reputation: 2804
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
Upvotes: 0
Views: 1282
Reputation: 2804
In the end, I did the conversion in the where statement and got rid of the virtual attributes:
def self.time_available
where("cast(start_time as time) <= cast(now() as time) and cast(end_time as time) >= cast(now() as time)")
end
Hope that helps someone
Upvotes: 0
Reputation: 20639
If you rewrite this as an equivalent method definition then it might be easier to figure out.
def self.time_range
a = DateTime.parse(start_time_am)
where("#{a} <= ?", Time.now.strftime('%H'))
end
Where is start_time_am coming from? The method doesn't have any arguments.
Upvotes: 3