1

我使用 activerecord 将一些 Timesheet 对象组合在一起

scope :grouped_by_user_with_total_time, lambda {
  group(:user_id, :day).select('user_id, SUM(time_worked) AS time_total, day, editable, approvable, accepted, comments')
}

在我这样做之后,现在当我尝试在分组对象上调用批准方法时,我得到了错误

Couldn't find TimeSheet without an ID

它突出了我方法中的第三行

def approve
@time_sheets = []
*t = TimeSheet.find(params[:time_sheets])**  
if t.instance_of?(Array)
  @time_sheets = t
else
  @time_sheets << t
end
successful = []
unsuccessful = []

@time_sheets.each do |timesheet|
  unless timesheet.approved
    timesheet.approve
    if timesheet.save
      successful << timesheet
    else
      unsuccessful << timesheet
    end
  end
end

我对此不是很有经验,我不确定如何检查我params[:time_sheets]的是否为 nil,这可能是问题所在。任何帮助表示赞赏。

4

1 回答 1

-1

Yes params[:time_sheets] being passed as nil would cause this error.

def approve
if params[:time_sheets]
@time_sheets = []
*t = TimeSheet.find(params[:time_sheets])**  
if t.instance_of?(Array)
  @time_sheets = t
else
  @time_sheets << t
end
successful = []
unsuccessful = []

@time_sheets.each do |timesheet|
  unless timesheet.approved
    timesheet.approve
    if timesheet.save
      successful << timesheet
    else
      unsuccessful << timesheet
    end
  end
end
end

By adding a check with if params[:time_sheets] we can ensure the method only runs if the params[:time_sheets] is not nil. However it seems that you might be having a problem in passing your params. If you post your code where you show where you pass the params we could find out why it's passing nil.

于 2013-08-26T01:08:11.140 回答