0

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 }})
Senthil
  • 946
  • 1
  • 14
  • 34

1 Answers1

0
  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.

Adler Hsieh
  • 477
  • 3
  • 10
  • Thanks for quick response , whether JBuilder handles eager load ? – Senthil Oct 02 '14 at 11:50
  • jBuilder is only responsible for building view template. I recommend it because your logic in building the json format will make the code a little complicated. I think eager load will call everything belongs to the `Scheme` if you use `include()` and the association is `has_many` – Adler Hsieh Oct 02 '14 at 12:55