我試圖實現Rails的API,和我有以下兩種模式:Rails的API渲染關聯對象名稱,而不是ID的JSON
事件
belongs_to :location accepts_nested_attributes_for :location
位置
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
請給我建議,我怎麼能做到這一點。
你在哪裏要顯示'location.name',而不是'location_id'? –
如果您詢問的路線是包含位置的名稱而不是id,那麼會有一個名爲friendly-id的gem來解決您的問題。 –
你在事件和地點之間有任何關係嗎? –