0

I have an annoying issue with this particular situation:

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

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

As you can see, this controller is under a folder name "api". This controller is connected to a "artists_controller" controller:

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

So I call to that function using 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'
});

But I get this error when the save action is successful:

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

Only in the case when the album was saved, if there was any error the ajax call returns this content for example:

$.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"]}}

Which is correct, but how can I avoid the 'album_url' error?

I'm assuming that this error could be happening because we are using this controller as a resource in the route.rb file, so the correct path should be something like "api_artists_album_url" but how can I change that to the correct variable?

I'm using gem 'rails', '3.2.12'

Thanks

diegocst90
  • 61
  • 7

1 Answers1

0

you should specify namespace in the respond_to call to make this work:

class Api::AlbumsController < ApplicationController
  respond_to :json

  def create
    respond_with :api, Album.create(params[:album])
  end
end
Vasiliy Ermolovich
  • 24,459
  • 5
  • 79
  • 77