Rails controller respond_with json from two models -


i want respond_to :json in locations_controller both location , beer models.

my locations controller looks this

class locationscontroller < applicationcontroller respond_to :html, :json   # /locations   # /locations.json   def index     @locations = location.all      respond_with(@locations,:only => [:id,:lat,:long,:name,:street_address,:place,:route],:methods => [:main_url, :beer_name])   end  

@beer belongs_to :location , :name beer model added above location response. beers_controller.

class beerscontroller < applicationcontroller   respond_to :html, :json   # /beers   # /beers.json    def index     @beers = beer.where(:location_id => params[:location_id])     respond_with(@beers,:only => [:id,:name,:description,:price,:style,:location_id, :brewery, :available],:methods => [:label_url])         end 

how can that? thanks.

take at: https://github.com/nesquena/rabl

rabl provides simple way retrieve relationships on objects, , can build json in clean , easy way.

as beer model belongs_to location, have 2 options:

  • if location has_one beer, can access direcly location.beer.name, meaning, name beer location.

  • if location has_many beer(s), can make loop iterate on
    every beer location:

code:

location.beers.each |beer|     puts beer.name end 

Comments

Popular posts from this blog

python - How to create a legend for 3D bar in matplotlib? -

java - Multi-Label Document Classification -

php - Dynamic url re-writing using htaccess -