Filter json render in Rails

后端 未结 2 2048
栀梦
栀梦 2020-12-23 18:03

What is the best way if i would like to only return :id and :name fields in JSON

So far i have:

format.json { render :json => @contacts.map(&:         


        
2条回答
  •  清酒与你
    2020-12-23 18:36

    You can pass :methods to to_json / as_json

    format.json do
      render :json => @contacts.map { |contact| contact.as_json(:only => :id, :methods => :name) }
    end
    

    Alternatively you can just build up a hash manually

    format.json do
      render :json => @contacts.map { |contact| {:id => contact.id, :name => contact.name} }
    end
    

    See: http://api.rubyonrails.org/classes/ActiveModel/Serializers/JSON.html#method-i-as_json

提交回复
热议问题