【问题标题】:Having the following Error: NoMethodError in Posts#show出现以下错误:Posts#show 中的 NoMethodError
【发布时间】:2017-01-02 03:47:00
【问题描述】:

我不断收到以下错误。我正在尝试开发自己的博客平台,以此作为我学习和变得更好的一种方式。

错误:

显示 /home/ubuntu/workspace/app/views/posts/show.html.erb 在哪里 第 36 行提出:

未定义的方法`post_cmets_path' 你的意思是?帖子路径

app/views/posts/show.html.erb

<h2>Add a comment:</h2>
<%= form_for([@post, @post.comments.build]) do |f| %>
  <div class="field">
    <%= f.label :author %><br />
    <%= f.text_field :author %>

config/routes.rb

Rails.application.routes.draw do
  get 'welcome/index'

  resources :posts
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
  root :to => "posts#index"
end

【问题讨论】:

  • 发布您的路线文件。
  • Rails.application.routes.draw do get 'welcome/index' resources :posts # 有关此文件中可用 DSL 的详细信息,请参阅guides.rubyonrails.org/routing.html root :to => "posts#index"结束

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4 ruby-on-rails-3.2


【解决方案1】:

您没有嵌套在 posts 资源中的 comments 资源(或根本没有嵌套),因此您无法使用帖子中的评论创建 URL。

您需要先定义您的 cmets 路由,然后才能为它们生成 URL。

如果你想将它们嵌套在posts 中,你应该修改你当前的resources :posts 行:

resources :posts do
  resources :comments
end

您的路由文件中的resources 生成帮助方法,Rails 使用这些方法为模型生成 URL,在本例中为 post_comments_path

【讨论】:

    【解决方案2】:

    您可能需要更新它以使其看起来像

    routes.rb

    resources :posts do
      resources :comments
    end
    

    这样做后,您应该可以在控制台中使用rake routesrails routes 看到新路由。

    【讨论】:

      【解决方案3】:

      您必须编辑对 routes.rb 文件的以下更改,然后重试

         resources :posts do
            resources :comments
          end
      

      【讨论】:

        【解决方案4】:

        您的路线文件不正确。将以下代码放在您的 routes.rb 中

        Rails.application.routes.draw do
          get 'welcome/index'
        
          resources :posts do
            resources :comments
          end
        
          # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
          root :to => "posts#index"
        end
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-08-08
          • 1970-01-01
          • 2016-01-05
          相关资源
          最近更新 更多