Ruby on rails 未定义的方法'id';for nil:NilClass由项目侧栏链接引起
我正在尝试使用“闭包树”gem实现一个评论系统,当我尝试单击指向项目概要文件的评论页面(评论项目路径)的链接时,出现以下错误: 该错误指的是my project_侧栏部分中的一行,其中包含指向项目实例不同页面的多个链接(上面看到的注释页面以及其他几个路由项目页面) 我的视图/projects/_project_sidebar.html.erbRuby on rails 未定义的方法'id';for nil:NilClass由项目侧栏链接引起,ruby-on-rails,ruby-on-rails-4,rails-routing,nomethoderror,Ruby On Rails,Ruby On Rails 4,Rails Routing,Nomethoderror,我正在尝试使用“闭包树”gem实现一个评论系统,当我尝试单击指向项目概要文件的评论页面(评论项目路径)的链接时,出现以下错误: 该错误指的是my project_侧栏部分中的一行,其中包含指向项目实例不同页面的多个链接(上面看到的注释页面以及其他几个路由项目页面) 我的视图/projects/_project_sidebar.html.erb THE LINK_TO JUST BELOW IS HIGHLIGHTED IN THE ERROR <%= link_to "+ Submit
THE LINK_TO JUST BELOW IS HIGHLIGHTED IN THE ERROR
<%= link_to "+ Submit Task", new_task_path(:project_id=> @project.id), :class => "btn btn-info col-md-12" %>
<br/>
<ul class="sidebar-menu">
<div class="sidebar-header">
<h4 class="head">Explore this Project</h4>
</div>
<li>
<h4>
<a href="<%= project_path(@project) %>">
Overview
</a>
</h4>
</li>
<li>
<h4>
<a href="<%= tasks_project_path(@project) %>">
Tasks
</a>
</h4>
</li>
<li>
<h4>
<a href="<%= comments_project_path(@project) %>">
Discussion
</a>
</h4>
</li>
</ul>
我的评论控制器:
def comments
@title = "Project Comments"
@project = Project.find(params[:id])
@comments = @project.comments
render 'show_project_discussion'
end
class CommentsController < ApplicationController
before_filter :authenticate_user!, only: [:create, :new, :edit, :update, :delete]
def index
@comments = Comment.all
end
def new
@project_id = params[:project_id]
@comment = Comment.new
end
def create
@project = Project.find(params[:Project_id])
@comment = current_user.own_comments.build(comment_params)
if @comment.save
flash[:success] = 'Your comment was posted!'
redirect_to root_url
else
render 'new'
end
end
private
def comment_params
params.require(:comment).permit(:body, :project_id, :user_id)
end
end
非常感谢您的帮助。我想这是关于您的
routes.rb中的操作顺序
这:
为所有7个操作(索引、显示、新建、编辑、更新、销毁、创建)生成正则表达式匹配器
index
的正则表达式与您尝试使用的成员路由匹配:
/projects/1/comments
由于routes返回第一个匹配的值,因此请求由注释#索引
处理,其中未设置@project
。因此,当您在nil
上调用id
时,就会出现错误
为了解决这个问题,我建议限制资源生成的匹配器
:
resources :projects do
resources :comments, except: [:index]
end
Rails.application.routes.draw do
devise_for :users
resources :users do
collection do
patch :update, as: :update
end
member do
get :following, as: :users_following
get :profile, as: :profile
end
end
resource :profile, only: [:show, :update]
resources :projects do
match '/settings'=>'projects#settings', :via=>:get, :as=>:settings
match '/invites'=>'projects#invites', :via=>:get, :as=>:invites
match '/invite_admin'=>'projects#invite_admin', :via=>:patch, :as=>:invite_admin
get :autocomplete_user_email, :on => :collection
end
resources :projects do
resources :comments
member do
get :projectadmins
get :followers
get :tasks
get :comments
end
end
resources :tasks
resources :comments
end
resources :comments
/projects/1/comments
resources :projects do
resources :comments, except: [:index]
end