Rails:未定义方法“strftime”;对于 nil:NilClass,但值(不带 strftime)返回 OK
我对(rails 3)activerecord 查询有一个奇怪的问题。
如果我将查询#1(下面)提交到视图(下面),一切正常...但是如果我提交查询#2(下面),我会得到“undefined method `strftime' for nil:NilClass”
...但是,如果我从查询 #2 中删除 strtime 字符串,它会返回未格式化的时间。
“专业特长”是一个 has_many :through 表;我认为这与它有关......但我不太清楚是什么。
知道发生了什么事吗?感谢所有建议:
查询#1(工作正常)
@professionals = Professional.all(:include => :user, :conditions => ["users.first_name = ? AND users.last_name = ?", params[:name][:first], params[:name][:last]])
查询#2(中断 strtime)
@professionals = Professional.all(:include => [:user, :professional_specialties], :conditions => ["professional_specialties.profession_type_id = ?", params[:profession_type]] )
查看
<% @professionals.each do |p| %>
<tr>
<td><%= link_to("%s %s" % [p.user.first_name, p.user.last_name], p) %></td>
<td><%= p.business %></td>
<td><%= p.user.role.name %></td>
<td><%= p.user.created_at %></td>
<td><%= p.user.last_sign_in_at.strftime("%Y") %></td>
</tr>
<% end %>
I have an odd problem with a (rails 3) activerecord query.
If I submit query #1 (below) to the view (below) everything works fine...but if I submit query #2 (below), I get "undefined method `strftime' for nil:NilClass"
...However, if I strip the strtime string away from query #2, it returns the unformatted time just fine.
"Professional specialties" is a has_many :through table; I'm assuming that has something to do with it...but I can't quite figure out what.
Any idea what's going on? All suggestions appreciated:
Query #1 (works fine)
@professionals = Professional.all(:include => :user, :conditions => ["users.first_name = ? AND users.last_name = ?", params[:name][:first], params[:name][:last]])
Query #2 (breaks strtime)
@professionals = Professional.all(:include => [:user, :professional_specialties], :conditions => ["professional_specialties.profession_type_id = ?", params[:profession_type]] )
View
<% @professionals.each do |p| %>
<tr>
<td><%= link_to("%s %s" % [p.user.first_name, p.user.last_name], p) %></td>
<td><%= p.business %></td>
<td><%= p.user.role.name %></td>
<td><%= p.user.created_at %></td>
<td><%= p.user.last_sign_in_at.strftime("%Y") %></td>
</tr>
<% end %>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我最好的猜测是这两个查询会给出不同的结果集。在第二个结果集中,一个或多个用户的
last_sign_in_at
列具有NULL
值。在 Rails 控制台(应用程序目录中的
rails console
)中运行Professional.all(...).map(&:users)
,并仔细检查它们是否都有有效的时间戳。My best guess would be that the two queries give you different resultsets. In the second resultset, one or more of the users has a
NULL
value for thelast_sign_in_at
column.Run
Professional.all(...).map(&:users)
in the Rails console (rails console
in your application directory), and double-check that they all have valid timestamps.