ruby:未定义的方法`’为nil:NilClass
更新后,当我尝试启动我的ruby应用程序时,我有一个错误:
undefined method `[]' for nil:NilClass
提取的来源(第8行):
8: app/models/account.rb:68:in `find_mak' app/views/layouts/_js_api_init.html.erb:8:in `block in _app_views_layouts__js_api_init_html_erb___274999121_65047152' app/views/layouts/_js_api_init.html.erb:1:in `_app_views_layouts__js_api_init_html_erb___274999121_65047152' app/views/layouts/logged_out.html.erb:17:in `_app_views_layouts_logged_out_html_erb__713588534_51277824' app/controllers/leads_controller.rb:11:in `new' config/initializers/newrelic_instrumentation.rb:30:in `call' config/initializers/newrelic_instrumentation.rb:51:in `call'
但是,我不明白第8行发生了什么,我怎么能贬低这个错误? 如果您需要更多信息以便回答,请写一条评论。 谢谢。
class Account include Mongoid::Document include Mongoid::Timestamps attr_accessible :org_name, :time_zone field :org_name ... ... def self.find_mak where( org_name: 'Mak' ).first end end
现在在其他地方出错
'json', id: 'register', :class => 'custom register' do %>
你认为这一点:
Account.find_mak.api_key
会导致你看到的错误
Account.find_mak
如果数据库中不存在匹配的记录,则返回nil。
我的建议是不要在视图中直接使用#{Account.find_mak.api_key}
,而是将其分配给控制器中的变量,然后可以检查nil:
def some_action @account = Account.find_mak if @account.nil? # handle this case, ie a redirect to 404 end end
然后在您的视图中,您可以使用该变量并确定它不能为零:
<%= form_tag "/apps/#{@accpunt.api_key}/users", #...