2013-03-24 75 views
0

response_with路由错误我有这种特殊情况下一个恼人的问题:与型号名称

#Controller> api/albums_controller.rb 
class Api::AlbumsController < ApplicationController 
    respond_to :json 

    def create 
    respond_with Album.create(params[:album]) 
    end 
end 

正如你可以看到,这个控制器是下一个文件夹名称“API”。该控制器连接到“artists_controller”控制器:

#routes.rb 
namespace :api do 
    resources :artists do 
    resources :albums 
    end 
end 

所以我使用jQuery调用该函数:

$.ajax({ 
    url: '/api/artists/1/albums', 
    method: 'POST', 
    dataType: 'json', 
    data: 'album[year]=2000&album[genre_id]=1&album[name]=FDFSD&album[artist_id]=1' 
}); 

但是,当攒动我得到这个错误是成功的:

NoMethodError in Api::AlbumsController#create 
undefined method `album_url' for #<Api::AlbumsController:0xc0ebdb4> 

只有在专辑保存的情况下,如果有任何错误,ajax调用返回此内容,例如:

$.ajax({ 
    url: '/api/artists/1/albums', 
    method: 'POST', 
    dataType: 'json', 
    data: 'album[year]=2000&album[genre_id]=1' 
}); 
//Results 
{"errors":{"name":["can't be blank"],"artist":["can't be blank"]}} 

哪个是正确的,但我怎样才能避免“ALBUM_URL”的错误?

我假设这个错误可能会发生,因为我们在route.rb文件中使用这个控制器作为资源,所以正确的路径应该是类似“api_artists_album_url”的东西,但我该如何改变它到正确的变量?

我使用的宝石 '轨', '3.2.12'

感谢

回答

0

你应该在respond_to调用指定的命名空间,以使这项工作:

class Api::AlbumsController < ApplicationController 
    respond_to :json 

    def create 
    respond_with :api, Album.create(params[:album]) 
    end 
end