我总是收到这样的错误消息:
undefined method 'firm_size' for nil:NilClass
当迭代一个集合并遇到一些零情况时。
我通常必须进入我的视图并if
围绕这个特定属性添加一个语句来处理 nil 情况。
这似乎是一种非常不干燥的方法。
在 Rails 中是否有更优雅的方式来处理这些类型的案例?不仅是nil
集合中的对象,而且可能具有属性的对象nil
- 这实际上就是这里发生的事情。
谢谢。
编辑 1
有关此特定错误实例的更多上下文:
这在我Scores#index
看来——
<% @clients.each do |client| %>
<tr>
<td><%= "First Client" %></td>
</tr>
<tr>
<td>Firm Size</td>
<td><%= best_in_place client.score, :firm_size, :type => :input, :nil => "Add Score for Firm Size" %></td>
这是我scores_controller.rb
的相关部分:
class ScoresController < ApplicationController
before_filter :load_clients
def index
@weight = current_user.weight
@scores = current_user.scores
respond_to do |format|
format.html # index.html.erb
format.json { render json: @scores }
end
end
private
def load_clients
@clients = current_user.clients
end
end
这是服务器日志:
Started GET "/scores" for 127.0.0.1 at 2012-10-10 18:38:05 -0500
Processing by ScoresController#index as HTML
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1
Weight Load (0.2ms) SELECT "weights".* FROM "weights" WHERE "weights"."user_id" = 1 LIMIT 1
Client Load (0.3ms) SELECT "clients".* FROM "clients" WHERE "clients"."user_id" = 1
Score Load (10.9ms) SELECT "scores".* FROM "scores" WHERE "scores"."client_id" = 1 LIMIT 1
Score Load (0.3ms) SELECT "scores".* FROM "scores" WHERE "scores"."client_id" = 2 LIMIT 1
Rendered scores/index.html.erb within layouts/application (276.6ms)
Completed 500 Internal Server Error in 283ms
这是有问题的记录(即client.score
何时client.id = 2
)
1.9.3p194 :089 > d = Client.find(2)
Client Load (0.2ms) SELECT "clients".* FROM "clients" WHERE "clients"."id" = ? LIMIT 1 [["id", 2]]
=> #<Client id: 2, name: "Jack Daniels", email: "jack@abc.com", phone: 1234567890, firm_id: 2, created_at: "2012-09-05 19:26:07", updated_at: "2012-10-07 02:44:51", user_id: 1, last_contact: "2012-02-10", vote: false, vote_for_user: false, next_vote: "2012-07-12", weighted_score: nil>
1.9.3p194 :090 > d.score
Score Load (0.4ms) SELECT "scores".* FROM "scores" WHERE "scores"."client_id" = 2 LIMIT 1
=> nil
正如我之前所说,每当遇到 nil 记录(或属性)时都会引发此错误。在这种特殊情况下,零记录用于2nd
未分配分数的客户记录。