Filter json render in Rails

后端 未结 2 2044
栀梦
栀梦 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:34

    Rails 3 supports following filter options. as simple as is

    respond_to do |format|
      format.json { render json: @contacts, :only => [:id, :name] }
    end  
    
    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题