2017-03-08 55 views
0

我有一個Rails應用程序建立在一個「API V1」結構:Rails的 - 正確的位置

module API::V1 
    class MessagesController < AuthenticatedAPIController 

而且我有屬於一個主題的消息控制器, 是這樣的:

namespace :api, defaults: { format: 'json' } do 
    namespace :v1 do 
     resources :topics do 
     resources :messages, name_prefix: 'topic_', only: [:index, :create] 
     end 

我試圖建立的位置,但所有我嘗試我不斷收到:

NoMethodError (undefined method `API_V1_topic_message_url' for #<API::V1::MessagesController:0x6aa5f68>): 

(或者simila RS)。

這裏就是我想:

if @message.save 
    render json: @message, status: :created, location: [:api, :v1, @topic, @message] 

我也試過:

location: [:api, :v1, @topic, @message] 
location: [@topic, @message] 
location: [@message] 
location: [:API, :V1, @topic, @message] 
location: api_v1_topic_message(@topic, @message) 

你的名字!哈哈 什麼是正確的做法呢?

在此先感謝。

編輯路線:

  api_v1_topic_messages GET  /api/v1/topics/:topic_id/messages(.:format)            api/v1/messages#index {:format=>"json", :name_prefix=>"topic_"}           
           POST  /api/v1/topics/:topic_id/messages(.:format)            api/v1/messages#create {:format=>"json", :name_prefix=>"topic_"} 

所以答案是:

api_v1_topic_messages_url(@topic)  
+0

當你在命令行上運行'rake routes' ...它認爲*路徑路徑變成了什麼? –

+1

@TarynEast我更新了這個問題。所以你殺了它。你能否在回答中改變你的評論,以便我能接受它? –

+0

你可以嘗試調用你的模塊API而不是API? Module Api :: V1 –

回答

1

當您運行命令行rake routes ...是什麼想的路由路徑變爲?

我問,因爲經常有細微的差異:) 在這種情況下 - 您使用的路線都需要messages部分被複數化。