Rails Object Relationships and JSON Rendering

前端 未结 2 696
再見小時候
再見小時候 2020-11-30 20:42

Disclaimer, I know very little about Rails. I\'ll try to be succinct. Given the following model relations in Rails:

cl         


        
相关标签:
2条回答
  • 2020-11-30 21:14

    By default you'll only get the JSON that represents modelb in your example above. But, you can tell Rails to include the other related objects as well:

    def export
      @export_data = ModelA.find(params[:id])
      respond_to do |format|
        format.html
        format.json { render :json => @export_data.to_json(:include => :modelb) }
      end
    end
    

    You can even tell it to exclude certain fields if you don't want to see them in the export:

    render :json => @export_data.to_json(:include => { :modelb => { :except => [:created_at, updated_at]}})
    

    Or, include only certain fields:

    render :json => @export_data.to_json(:include => { :modelb => { :only => :name }})
    

    And you can nest those as deeply as you need (let's say that ModelB also has_many ModelC):

    render :json => @export_data.to_json(:include => { :modelb => { :include => :modelc }})
    

    If you want to include multiple child model associations, you can do the following:

    render :json => @export_data.to_json(include: [:modelA, :modelB, :modelN...])
    
    0 讨论(0)
  • 2020-11-30 21:28

    If you want a more flexible approach to rendering json, you can consider using the gem jbuilder: https://github.com/rails/jbuilder

    It allows you to render custom attributes, instance variables, associations, reuse json partials in a convenient way.

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