Rails 3:对未定义的URL帮助程序的响应有错误

时间:2012-09-28 20:52:23

标签: ruby-on-rails

我有一个Artwork模型,现在只能由API端点操作。 (你会明白为什么这很重要)。这些API端点在我的routes.rb文件中声明为:

namespace :api do
  namespace :v1, :defaults => { :format => :json } do
    resources :artworks, :only => [:create, :destroy, :index, :show, :update]

这导致以下路线:

api_v1_artworks GET        /api/v1/artworks(.:format)                                             api/v1/artworks#index {:format=>:json}
                POST       /api/v1/artworks(.:format)                                             api/v1/artworks#create {:format=>:json}
api_v1_artwork  GET        /api/v1/artworks/:id(.:format)                                         api/v1/artworks#show {:format=>:json}
                PUT        /api/v1/artworks/:id(.:format)                                         api/v1/artworks#update {:format=>:json}
                DELETE     /api/v1/artworks/:id(.:format)                                         api/v1/artworks#destroy {:format=>:json}

相关代码:

class Api::V1::ArtworksController < Api::V1::ApiController
  def create
    artwork = Artwork.create(artwork_params)

    respond_with artwork
  end

问题

#create成功时,respond_with会窒息:

`undefined method `artwork_url' for #<Api::V1::ArtworksController:0x007fea1b4c67f8>`

期望HTTP位置的帮助程序为artwork_url。如何告诉它使用api_v1_artwork_url代替?我可以为URL帮助器设置别名吗?

1 个答案:

答案 0 :(得分:35)

在这种情况下,您需要为响应者指定名称空间。尝试:

respond_with :api, :v1, artwork