简体   繁体   English

Rails控制器来自两个模型的response_with json

[英]Rails controller respond_with json from two models

I want to respond_to :json in my locations_controller from both my location and beer models. 我想从我的位置和啤酒模型中对我的location_controller中的respond_to :json进行respond_to :json

My locations controller looks like this 我的位置控制器如下所示

class LocationsController < ApplicationController
respond_to :html, :json
  # GET /locations
  # GET /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 and I would like :name from the beer model to be added to the above location response. @beer Emirates_to:location,我希望将啤酒模型中的:name添加到上述location响应中。 This is my beers_controller . 这是我的beers_controller

class BeersController < ApplicationController
  respond_to :html, :json
  # GET /beers
  # GET /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 I do that? 我怎样才能做到这一点? Thanks. 谢谢。

Take a look at: https://github.com/nesquena/rabl 看一下: https : //github.com/nesquena/rabl

Rabl provides a simple way for you to retrieve all relationships on objects, and you can build your json in a clean and easy way. Rabl为您提供了一种检索对象上所有关系的简单方法,并且您可以以一种干净,轻松的方式构建json。

As your beer model belongs_to a location, you have two options: 由于您的啤酒模型属于某个位置,因此有两种选择:

  • If location has_one beer, you can access direcly location.beer.name , this meaning, the name from the beer from this location. 如果location has_one啤酒,则可以直接访问location.beer.name ,这意味着此位置的啤酒名称。

  • If you location has_many beer(s), you can make a loop to iterate on 如果您定位has_many啤酒,则可以进行循环以迭代
    every beer for a location: 每个位置的啤酒:

Code: 码:

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

the rabl gem looks like a good way to go but I decided to add this to my location model Rabl宝石看起来很不错,但是我决定将其添加到我的位置模型中

def as_json(options={})
    super(:only => [:id,:lat,:long,:name,:street_address,:place,:route], :methods => [:main_url],
          :include => {
            :beers => {:only => [:name]}
          }
    )
  end

This does the trick for me. 这对我有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM