【问题标题】:"undefined method `post_comments_path' for #<#<Class:0x4e6ec28>:0x4e6e3d0>" in rails 4.0.4“#<#<Class:0x4e6ec28>:0x4e6e3d0> 的未定义方法 `post_comments_path'”在 rails 4.0.4
【发布时间】:2014-03-27 18:16:53
【问题描述】:
undefined method `post_comments_path' for #<#<Class:0x4e6ec28>:0x4e6e3d0>

我在创建与帖子关联的评论时遇到此错误。

<%= form_for([@post, @post.comments.build]) do |f| %>

上面是我收到错误的表单部分..

我在 cmets 控制器中的代码:

def create
  @post = Post.find (params[:post_id])
  @comment = @post.comments.create(params[:comments].permit(:commenter, :body))
  redirect_to post_path(@post)
end

请指出我错在哪里。我是 ruby​​ on rails 的新手。

我的路线.rb:

Blog::Application.routes.draw do
  resources :posts 
  resources :comments
  root to:"welcome#index"
  get "welcome/index"

我的 rake 路线:

        posts GET    /posts(.:format)             posts#index
              POST   /posts(.:format)             posts#create
     new_post GET    /posts/new(.:format)         posts#new
    edit_post GET    /posts/:id/edit(.:format)    posts#edit
         post GET    /posts/:id(.:format)         posts#show
              PATCH  /posts/:id(.:format)         posts#update
              PUT    /posts/:id(.:format)         posts#update
              DELETE /posts/:id(.:format)         posts#destroy
     comments GET    /comments(.:format)          comments#index
              POST   /comments(.:format)          comments#create
  new_comment GET    /comments/new(.:format)      comments#new
 edit_comment GET    /comments/:id/edit(.:format) comments#edit
      comment GET    /comments/:id(.:format)      comments#show
              PATCH  /comments/:id(.:format)      comments#update
              PUT    /comments/:id(.:format)      comments#update
              DELETE /comments/:id(.:format)      comments#destroy
         root GET    /                            welcome#index
welcome_index GET    /welcome/index(.:format)     welcome#index

我编辑的路线.rb ::

Blog::Application.routes.draw do
  resources :post  do
    resources :comments
  end
  root to:"welcome#index"
  get "welcome/index"
end

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:

    您尝试使用nested resources,但您没有在routes.rb 中定义它。你应该有:

    resources :posts do
      resources :comments
    end
    

    这应该有效。

    【讨论】:

    • 如果我这样做了,那么我的服务器没有启动..说“语法错误,意外 $end,期待关键字_end (SyntaxError)”
    • @user3322822 你一定弄坏了一些东西。请再次显示您的 routes.rb。 PS 确保 endroutes.rb 文件的末尾。
    • 可能删除了Blog::Application.routes.draw do 或类似的
    • @user3322822 你在resources :comments 之后忘记了end。请仔细复制/粘贴。顺便说一句,我认为你应该学习一些 Ruby 基础知识......
    • 是的...@MarekLipka
    猜你喜欢
    • 2020-05-30
    • 1970-01-01
    • 1970-01-01
    • 2016-12-11
    • 2020-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-12
    相关资源
    最近更新 更多