2015-07-01 23 views
0
的形式

我試圖實現Rails的API,和我有以下兩種模式:Rails的API渲染關聯對象名稱,而不是ID的JSON

  1. 事件

    belongs_to :location accepts_nested_attributes_for :location 
    
  2. 位置

    has_many :events 
    

event = Event.all 

我越來越location_id與其他數據,但我想說明location.name,而不是location_id的API請求索引路徑即 localhost:3000/api/events

目前我m到處響應,

[{"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

請給我建議,我怎麼能做到這一點。

+0

你在哪裏要顯示'location.name',而不是'location_id'? –

+0

如果您詢問的路線是包含位置的名稱而不是id,那麼會有一個名爲friendly-id的gem來解決您的問題。 –

+0

你在事件和地點之間有任何關係嗎? –

回答

1
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

+0

ActionController :: UnknownFormat – Adt

+0

你可以粘貼這個請求的日誌嗎? –

+0

http://pastebin.com/wmTqVJKA – Adt