user10223422
user10223422

Reputation: 47

How to set identifiers an integer in Rails?

I have an API method that returns JSON floating-point identifiers (3971.0). Although in fact an integer (3971) should be output. How can this be remedied?

def index
  @users = User.all

  render json: @users
end

Upvotes: 0

Views: 30

Answers (1)

If you still want to go with solution using ActiveModel::Serializer, then you can do it as

  1. You need add this gem 'active_model_serializers'
  2. You need create a serializer for your resource rails g serializer user
  3. That will create a file user_serializer.rb under app/serializer
  4. Inside the class, define the attributes in the following manner which you want to send back in your response attributes :user_id, :login, :name, :spr_work_id
  5. Let's say you want to modify the value of :spr_work_id to make it an integer then you have to define a method inside the serializer as so

    def spr_work_id
    
      self.object.spr_work_id.to_i
    
    end
    

In your controller replace render json: @users to @users.map{|user| UserSerializer.new(user).serializable_hash}

Upvotes: 1

Related Questions