Victor Castillo Torres Victor Castillo Torres - 4 months ago 10
Ruby Question

Rails returning UTC instead of just text with Postgresql

So I'm working with Rails (4.2.6) and PostgreSQL, I have a table which contains a field named

end_time
of type Time, the problem I have is the next:

SELECT end_time FROM group_periods;


Will result in:

| end_time |
| 08:00:00 |


As you can see it only brings the text that is contained in the field (
08:00:00
) but if I try to do It in Rails it will bring in
end_time
a Time Object even if I cast it to text

GroupPeriod.select("end_time")


Will result in:

=> #<ActiveRecord::Relation [#<GroupPeriod id:nil, end_time: "2000-01-01 08:00:00">]>


after I try to access to
end_time
object it brings a Time object for Ruby.

I also have tried, resulting in the same:

GroupPeriod.select("end_time::text")
GroupPeriod.select("to_char(end_time, 'HH24:MI') end_time")


How could I get the field
end_time
as a string so whenever I access the field I get the same result as Postgres?

EDIT



There is no chance to do a strftime and get te string format on every record due to I have thousands of records, that's the main reason I have already tried to cast the field as a text so rails would return a string instead of a Time object.

Answer

You could override the attribute accessor for end_time on the model and return the attribute before type casting

Something like

class GroupPeriod < ActiveRecord::Base
  ...

  def end_time
    self.end_time_before_type_cast
  end

  ...
end

Documentation