2014-12-08 33 views
0

我在Ruby on Rails路由中遇到問題。Ruby on Rails「無法爲MessagesController找到操作'create'

配置/ routes.rb中:

Rails.application.routes.draw do 

    resources :messages 

    root to: 'dashboards#show' 

end 

應用程序/控制器/ messages_controller.rb:

class MessagesController < ApplicationController 

    def index 
     # Do current user messages select from database here 
    end 

end 

連結messges:

<%= button_to 'messages', messages_path %> 

URL:

http://localhost:3000/messages 

錯誤:

The action 'create' could not be found for MessagesController 

爲什麼我有這個問題?我究竟做錯了什麼?爲什麼我得到這個錯誤?

回答

1

button_to方法默認完成了一個職位。當您將路由指定爲資源時,它會將帖子映射到#create方法。您需要定義該方法,停止使用帖子,或者修改您的routes.rb以將帖子發送到其他方法。從你如何使用它的外觀,你應該只修改button_to使用GET:

<%= button_to 'messages', messages_path, method: :get %> 
1

你不必在你的MessagesController一個創建方法:

def create 
end 
+0

如果我不需要什麼呢? – 2014-12-08 00:18:40

+0

當然'缺少模板消息/創建,應用/創建{:locale => [:en],:formats => [:html],:variants => [],:handlers => [:erb,:建築師,:生,:紅寶石,:咖啡,:jbuilder]}。 – 2014-12-08 00:19:34

1

button_to助手(link)的文件說:

...If no :method modifier is given, it will default to performing a POST operation

例如默認button_to會將該按鈕封裝在使用POST方法而不是GET方法的窗體中。具有GET請求的messages_path路徑將轉至MessagesController中的index方法,但帶有POST請求的message_path將路由至create方法。由於您沒有定義創建方法,因此會出現「未找到操作」錯誤。

爲了解決這個問題設置方法button_to爲GET:

<%= button_to 'messages', messages_path, method: 'GET' %> 
相關問題