Search code examples
ruby-on-railsactiverecordunix-timestamp

Getting Unix Time from Active Record ruby on rails


I have one table Bandwidth where I am saving user_traffic and created_at fields. I want to return user_name and created_at but I want date to be in Unix Time stamp in ruby on rails without using Query but by activerecord.

Bandwidth.all.select("user_traffic,created_at")

Above return both but in normal date format, but I want it to be in Unix

created_at: "2019-06-26 11:28:39", user_traffic: 0

I tried following and it works, but I could not get other column in this.

Bandwidth.find_by(id: 2).created_at.to_i

It return just timestamp which is perfect but how can I add other columns in this query. I think it is using model function to_i

=> 1561548975

Solution

  • If you don't need the relation later, you can use map to make any data format you want.

    EX:

    Bandwidth.all
             .select(:user_traffic, :created_at)
             .map{|b| [b.user_traffic, b.created_at.to_i]}