Home > Mobile >  I want to change the format of the timestamp for a particular model in Rails
I want to change the format of the timestamp for a particular model in Rails

Time:02-21

What I want to solve

I'm building a service with Nuxt and Rails, and I'm getting an error with timestamp from Rails due to the limited formatting used in Nuxt. Is there any way to change the format of created_at and updated_at in Rails? Specifically, I want it to look like YYYY-MM-DD hh:mm. I'm removing created_at and updated_at as an emergency measure.

Code

controller

class Api::V1::SchedulesController < ApplicationController

  def index
    schedules = Schedule.all
    
    render json:schedules, status: :ok
  end

CodePudding user response:

use jbuilder

in controller:

def index
  @schedules = Schedule.all
end

in view:

# app/views/api/v1/schedules/index.json.jbuilder

json.array! @schedules do |schedule|
  json.id schedule.id
  json.created_at schedule.strftime('%Y-%m-%d %H:%M')
  json.updated_at schedule.strftime('%Y-%m-%d %H:%M')
  
  # define other fields here...
  # ....
  # ....
end
  • Related