Rails API以JSON

时间:2015-07-01 10:49:39

标签: ruby-on-rails json

我试图实现Rails API,我有两个模型:

  1. 事件

    belongs_to :location   accepts_nested_attributes_for :location
    
  2. 位置

    has_many :events
    
  3. event = Event.all
    

    我正在获取location_id其他数据,但我想显示location.name代替location_id以获取索引路径的API请求,即 localhost:3000/api/events

    目前我的回复是

    [{"id":5,"name":"event420","description":"22","venue":"","contact":"","cost":"","created_at":"2015-07-01T05:49:22.738Z","updated_at":"2015-07-01T05:49:22.738Z","started_at":"2015-07-01T06:00:00.000Z","ended_at":"2015-07-01T06:30:00.000Z","owner_id":6,"city_id":null,"slug":"event420","clot_id":null,"location_id":10}]
    

    而不是location_id:10我想要Location.name

    请建议我,我该怎么做。

1 个答案:

答案 0 :(得分:3)

def index
    @events = Event.all
    respond_to do |format|
      format.html
      format.json { render :json => @events.to_json(:include => { :location => { :only => :name } }) }
    end
end

将此代码添加到events_controller