1

I'm using Ruby on Rails with ActiveRecords. And it really makes me sick about all this datatypes like DateTime, Time etc. I render all data-related things on frontend, so i need just simple int when retrieving Timestamp from DB. Can i do it without having so many to_int in my code?

Let's say i have migration like

class CreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
      t.string :email, null: false
      t.string :crypted_password, null: false
      t.string :password_salt, null: false
      t.string :persistence_token, null: false

      t.timestamps null: false
    end
  end
end

Then i do smth like

<%= @user.created_at =>

I have smth like 2015-02-11 14:11:04 UTC (because it's DateTime to_s in fact). While i need just 1423663864 (so i have to do smth like <%= @user.created_at.to_i =>). So it makes 4(!) conversion:

  1. DB 4 bytes int to DB string
  2. DB string to Ruby DateTime
  3. DateTime to int (the 4 bytes i had on first step)
  4. Ruby int to Ruby string
Ximik
  • 2,435
  • 3
  • 27
  • 53
  • That's not very clear. What database system are you using ? What are the data types used in your database and in active record ? and give a code example of the problem you're facing, and what the desired output would be – jazzytomato Feb 17 '15 at 13:56
  • you need to change the date format, which you want to show in the view? – amtest Feb 17 '15 at 14:00
  • You can simply save the datevalues as seconds since epoch which is an integer value. You can then decide how you want to format the value in your views. – dennis Feb 17 '15 at 14:03
  • @ThomasHaratyk, added some more info – Ximik Feb 17 '15 at 14:08
  • @amtest, no. I need it to work just with numbers. – Ximik Feb 17 '15 at 14:10
  • @dennis it's not a solution. E.g. if i want to use some DB triggers – Ximik Feb 17 '15 at 14:10

3 Answers3

1

You can create a file in config/initializers, let's say... date_format.rb with this:

Date::DATE_FORMATS[:default] = "%d-%m-%Y"

Then when you print a date, it will show with the format you wrote. P.D.: I'm sorry for my English.

  • It's still Date. Just changes to_s method. – Ximik Feb 17 '15 at 14:11
  • Set a format without blanks. You can print the string to a variable, and then convert it to int... But yeah, you're getting a lot of conversions so I don't know... –  Feb 17 '15 at 14:24
0

In ruby you can call to_i or to_f on a Date/Time/DateTime object to get the "seconds since epoch" value in integer or float format.

Max Williams
  • 32,435
  • 31
  • 130
  • 197
0

This will change the default output format of your dates to a unix timestamp representation :

Date::DATE_FORMATS[:default] = "%s"

According to the strftime documentation :

Seconds since the Unix Epoch:
%s - Number of seconds since 1970-01-01 00:00:00 UTC.

Read more about how datetime and timestamp types are handled in rails here (at the end of the answer)

Community
  • 1
  • 1
jazzytomato
  • 6,994
  • 2
  • 31
  • 44