我试图实现Rails API,我有两个模型:
事件
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
。
目前我的回复是
[{"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 :(得分: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