2

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.

3
  • post the output of this code too Commented Jun 15, 2015 at 16:55
  • you can use jbuilder. Is with rails by default If I am not wrong. Commented Jun 15, 2015 at 16:55
  • My guess (it is just a guess) is that you are trying to merge rails code to json code. Try either calling .to_json on the { 'disabled' => true} object or call as_json on the entire object after merging the object. Commented Jun 15, 2015 at 16:55

2 Answers 2

3

Try this

object.to_json(methods: [:disable])

in model.rb

def disable
  true
end
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.