我发送一个帖子请求到我的API工作正常,它创建一个新的记录.但是,在创建记录后,我在服务器日志中收到此错误
NoMethodError (undefined method `device_url' for #<Api::V1::DevicesController:0x007fa2f5dde5d8>):app/controllers/api/v1/devices_controller.rb:14:in `create'
这是我的创作动作
def create respond_with Device.create(params[:device]) end
我的所有资源都在Api#V1下命名,这是我的路由文件
# Api ('/api') namespace :api do # Version 1 ('/api/v1') namespace :v1 do # Locations ('/api/v1/locations') resources :locations # Videos ('/api/v1/videos') resources :videos # Devices ('/api/v1/devices') resources :devices end end
解决方法
对于HTML POST请求,在成功创建对象后,respond_with会重定向到对象的路径,即此处它将等同于
redirect_to Device.create(params[:device])
它重定向到device_url.但是,由于您在路由中设置了命名空间:设备,因此您需要为您的respond_with调用指定该设备
respond_with :api,:v1,Device.create(params[:device])