我对rails上的ruby还是新手,并不完全理解为什么我收到以下错误:
undefined local variable or method `user' for #<StatisticsController:0xb9a20d0>
代码:
class StatisticsController < ApplicationController
before_filter :authenticate, :only => [:index]
def index
@title = "Statistics"
@projects = Project.all
@data = []
Project.all.each do |project|
projdata = { 'name' => project.project_name.to_s,
'values' => [] }
['Pre-Sales','Project','Fault Fixing','Support' ].each do |taskname|
record = Effort.sum( :hours,
:joins => {:project_task => {:efforts => :user}},
:conditions => { "project_tasks.efforts.user_id" => user.id,
"project_tasks.project_id" => project.id,
"project_tasks.task_name" => taskname } )
projdata[ 'values' ].push( record )
end
@data.push( projdata )
end
end
end
更新
class StatisticsController < ApplicationController
before_filter :authenticate, :only => [:index]
def index
@title = "Statistics"
@projects = Project.all
@data = []
User.all.each do |user|
projdata = { 'name' => user.user_id.to_s,
'values' => [] }
['Pre-Sales','Project','Fault Fixing','Support' ].each do |taskname|
user = User.all
record = Effort.sum( :hours,
:joins => {:project_task => {:efforts => :user}},
:conditions => { "project_tasks.efforts.user_id" => user.id,
"project_tasks.project_id" => project.id,
"project_tasks.task_name" => taskname } )
projdata[ 'values'].push( record )
end
@data.push( projdata )
end
end
end
答案 0 :(得分:0)
在字符串:conditions => { "project_tasks.efforts.user_id" => user.id,
中,您为用户对象调用id,但它未在上面的代码中实例化。
答案 1 :(得分:0)
您使用的是devise
吗?使用current_user
代替user
。
修复您的代码:
User.all.each do |user|
projdata = { 'name' => user.user_id.to_s,
'values' => [] }
['Pre-Sales','Project','Fault Fixing','Support' ].each do |taskname|
record = Effort.sum( :hours,
:joins => {:project_task => {:efforts => :user}},
:conditions => { "project_tasks.efforts.user_id" => user.id,
"project_tasks.project_id" => project.id,
"project_tasks.task_name" => taskname } )
projdata[ 'values'].push( record )
end
@data.push( projdata )
end
所以:删除了流氓user=User.all
:)
问题:在一个地方你写user.user_id
而另一个你写user.id
。这是对的吗?
答案 2 :(得分:0)
您的更新根本不会遍历用户; user
现在是所有用户的集合。如果要为单个用户获取单独的统计信息,则需要对用户进行迭代。