2013-03-24 87 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