【问题标题】:Routing error on response_with with model name带有模型名称的 response_with 路由错误
【发布时间】:2013-03-24 19:55:48
【问题描述】:

我对这种特殊情况有一个烦人的问题:

#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”,但我怎样才能将其更改为正确的变量?

我正在使用 gem 'rails', '3.2.12'

谢谢

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 routes nested-routes


    【解决方案1】:

    您应该在 respond_to 调用中指定命名空间以使其工作:

    class Api::AlbumsController < ApplicationController
      respond_to :json
    
      def create
        respond_with :api, Album.create(params[:album])
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-10-04
      • 1970-01-01
      • 2015-07-07
      • 1970-01-01
      • 2013-12-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多