Matthew Smith
Matthew Smith

Reputation: 123

Rails - adding a field to a JSON response

I need to add a field to a JSON response.

def index
    if params[:competition_level]
      @competition_level_id = params[:competition_level].to_i
    end

   @matchups = @weekly_scoreboards

   # can I call @matchups[0].as_json to return a hash, and add a field?
   # let's see...

   @matchups[0].as_json.merge!({ 'disabled' => true} )

   # this returns @matchups[0] looking the way I need it to,
   # but it I look at @matchups[0].as_json again, the field I added is 
   # gone

   respond_to do |format|
      format.html { render }
      format.mobile { render }
      format.json {
          render :json => @matchups.to_json
      }
   end
end  

Not sure what's going on here. Been going over this for a few hours.

Upvotes: 2

Views: 3126

Answers (2)

jalkoby
jalkoby

Reputation: 379

If you need to add an extra field, you have to do the next:

respond_to do |format|
  # other formats
  format.json do
    json = @matchups[0].as_json
    json[0]['disabled'] = true
    render json: json
  end
end

This snippet is good for a case as above. If you have a more complex case, move all logic into an extra service. For example:

respond_to do |format|
  # other formats
  format.json do
    render json: MatchupSerializer.to_json(@matchups)
  end
end

# app/services/matchup_serializer.rb
module MatchupSerializer
  extend self

  def to_json(list)
    result = list.as_json
    result[0]['disabled'] = true
    # the rest of modifications
    result
  end
end

Upvotes: 1

Ravindra
Ravindra

Reputation: 150

Try this

object.to_json(methods: [:disable])

in model.rb

def disable
  true
end

Upvotes: 3

Related Questions