Rails - 向JSON响应添加字段

时间:2015-06-15 16:47:58

标签: ruby-on-rails json

我需要在JSON响应中添加一个字段。

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  

不确定这里发生了什么。已经过了几个小时。

2 个答案:

答案 0 :(得分:1)

如果您需要添加额外字段,则必须执行下一个字段:

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

此代码段适用于上述情况。如果您的案例更复杂,请将所有逻辑移至额外服务中。例如:

 
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

答案 1 :(得分:0)

试试这个

object.to_json(methods: [:disable])

in model.rb

def disable
  true
end