【发布时间】:2012-07-15 09:46:55
【问题描述】:
嗨,我正在尝试做一个 find_by_id,但如果 id 不存在调用此方法时,我会得到 nil 类
if current_user.admin?
@schedules = Schedule.all
elsif current_user.team_id?
@schedules = Schedule.find_by_team_id(current_user[:team_id])
end
错误
Schedule#index 中的 NoMethodError
显示 /Users//Sites/Rails/*/app/views/schedules/index.html.haml 第 44 行出现的位置:
nil:NilClass 的未定义方法 `each' 提取的源代码(第 44 行附近):
41: %th Location
42: %th{:style => "color: #675100;background: url(\"/img/sprites/alertboxes/bg-warning.png\") repeat-x #ffe68b;"} Manager
43: %tbody
44: - @schedules.each do |schedule|
45: %tr
46: %td= event_display(schedule.event)
47: %td
【问题讨论】:
-
这是正常行为,如果您使用 find_by_
如果没有找到该属性的记录,将返回 nil。另请注意,find_by_ 仅返回记录而不是 Enumerable。你应该 where(...) 或 find_all_by_ 代替。 -
你希望它做什么?
-
感谢 find_all_by 已解决问题
标签: ruby-on-rails if-statement controller null