Search code examples
ruby-on-railsruby-on-rails-4associationsto-json

Rails to_json including association with limit


I am rendering one record with with association like below

render :json => Scheme.where("id=?", params[:id]).first
                      .to_json(:include => { :navs => { :only => [:schemeCode,:navDate,:navValue] }})

Associations

Scheme has_many   navs
Nav    belongs_to scheme

I need to render only last record in Nav , but above will print all the navs since its one to many. I tried :limit => 1 and ordering it in desc , buts limit itself not working.Any help will be appreciated.

render :json => Scheme.where("id=?", params[:id]).first
                      .to_json(:include => { :navs => { :only => [:schemeCode,:navDate,:navValue], :limit => 1 }})

Solution

    1. If you're creating a complicated json format, try gem 'jbuilder' introduced in RailsCast to leave the structure to view.

      In your show.json.jbuilder view, make it something like:

      @scheme = Scheme.find(params[:id]) json.scheme @scheme.as_json json.extract! @scheme.navs.last, :schemeCode, :navDate, :navValue

      which will render the data in json format as well as keep your controller clean & neat.

    2. The use of Scheme.where("id=?", params[:id]).first in your code can be shortened as Scheme.find(params[:id]) if your id is unique.