【问题标题】:Ruby on Rails "The action 'create' could not be found for MessagesController"Ruby on Rails“找不到 MessagesController 的操作‘创建’”
【发布时间】:2014-12-08 00:14:39
【问题描述】:

我对 Ruby on Rails 路由有疑问。

config/routes.rb:

Rails.application.routes.draw do

  resources :messages

  root to: 'dashboards#show'

end

app/controllers/messages_controller.rb:

class MessagesController < ApplicationController

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

end

信息链接:

<%= button_to 'messages', messages_path %>

网址:

http://localhost:3000/messages

错误:

The action 'create' could not be found for MessagesController

为什么我有这个问题?我究竟做错了什么?为什么会出现此错误?

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    button_to 方法默认发布。当您将路由指定为资源时,它会将帖子映射到 #create 方法。您需要定义该方法,停止使用帖子,或修改您的 routes.rb 以将帖子发送到不同的方法。从您使用它的方式来看,您可能应该只修改 button_to 以使用 get:

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

    【讨论】:

      【解决方案2】:

      您的 MessagesController 中没有 create 方法:

      def create
      end
      

      【讨论】:

      • 如果我不需要它怎么办?
      • 当然还有Missing template messages/create, application/create with {:locale=&gt;[:en], :formats=&gt;[:html], :variants=&gt;[], :handlers=&gt;[:erb, :builder, :raw, :ruby, :coffee, :jbuilder]}.
      【解决方案3】:

      button_to 助手 (link) 的文档说:

      ...如果没有给出 :method 修饰符,它将默认执行 POST 操作

      例如,默认情况下button_to 会将按钮包装在使用 POST 方法而不是 GET 方法的表单中。带有 GET 请求的 messages_path 路径转到 MessagesController 中的 index 方法,但是带有 POST 请求的 message_path 被路由到 create 方法。由于您没有定义创建方法,因此您会收到“未找到操作”错误。

      要解决此问题,请将 button_to 的方法设置为 GET:

      <%= button_to 'messages', messages_path, method: 'GET' %>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-10-28
        • 1970-01-01
        • 1970-01-01
        • 2013-04-24
        • 2011-07-11
        相关资源
        最近更新 更多