E
E
Evgeny Skuridin2013-12-08 20:04:58
Ruby on Rails
Evgeny Skuridin, 2013-12-08 20:04:58

How to change attribute type in after_find in Rails 4?

There is a table with video. The duration is stored in seconds, but I want to give the output in a readable format "00:05:23". Now duration will get 0. How to drive a string there?

class Video < ActiveRecord::Base
  validates_numericality_of :duration

  after_find :format_duration

  protected
  def format_duration
    self.duration = Time.at(self.duration).gmtime.strftime('%R:%S')
  end
end

Answer the question

In order to leave comments, you need to log in

2 answer(s)
C
Cepega, 2013-12-08
@skuridin

Why not write a helper that will do it?

def  formated_duration(duration)
  Time.at(duration).gmtime.strftime('%R:%S')
end

Place this code in application_helper.rb or some similar place and call it from the view
<%= formated_duration(video.duration) %>

E
Evgeny Skuridin, 2013-12-08
@skuridin

Apparently, it can only be done using virtual attributes and attr_accessor.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question