ruby - Rails: active record saving time:type with unwanted format -


i have table call periodo attribute hour. pass time param in way

hour = time.parse( splitline[1] ) #where splitline[1] time in string periodo = periodo.new(:hour => hour.strftime("%h:%m")) periodo.save 

but active record save records in way hour: "2000-01-01 07:00:00" , set format in /config/initializers/time_formats.rb

time::date_formats[:default] = "%h:%m" date::date_formats[:default] = "%h:%m" 

and in en.yml

  en:     hello: "hello world"     time:       formats:         default: "%h:%m"     date:       formats:         default: "%h:%m" 

but records still saving year , month :( have save hour , minutes ???

greetings

date formats valid within application, not within database - responsible way time objects displayed users , not affect way data stored.

unfortunately, there no such concept time in database (at least haven't heard any, , trust me did search need in current project)

simplest solution

however, in many cases makes sense store time of event. in current project decided store in format of integer 60 * hour + minutes. unfortunately stopped in project. :(

one step further

you can create helper class (just scaffold - more work needed validations casting etc):

class simpletime   attr_accessor :hour, :minute    def initialize(hour, minute)      @hour, @minute = hour, minute   end    def self.parse(integer)     return if integer.blank?      new(integer / 60, integer % 60)   end    def to_i     60 * @hour + @minute   end end 

and override setter , getter:

class model < activerecord::base   def time     @time ||= simpletime.parse(super)   end    def time=(value)     super(value.to_i)   end end 

further fun

now there more things do. can example write extension simple_time active_record automatically redefine setters , getters list of passed attributes. can wrap in small gem , make real-world-proof (missing validations, string format parsers, handling _before_type_cast values etc).


Comments

Popular posts from this blog

javascript - Bootstrap Popover: iOS Safari strange behaviour -

Magento/PHP - Get phones on all members in a customer group -

session - Logging Out Using PHP -