makregistr
makregistr

Reputation: 131

ruby: undefined method `[]' for nil:NilClass

After update, when I try to start my ruby app, I have an error:

undefined method `[]' for nil:NilClass

Extracted source (around line #8):

8: <% account = Account.find_mak -%>

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'

but, I dont understand what was happened on line 8, how I can debuging this error?. If you need more information for answer, please write a comment. Thanks.

  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

now error in other place

<%= form_tag "/apps/#{Account.find_mak.api_key}/users",
               method: :post, remote: true,
               'data-type' => 'json',
               id: 'register',
               :class => 'custom register' do %>

Upvotes: 1

Views: 1468

Answers (1)

Thilo
Thilo

Reputation: 17735

This bit in your view:

Account.find_mak.api_key

will result in the error you see if

 Account.find_mak

returns nil, which it will if no matching record exists in your database.

My suggestion would be to not use #{Account.find_mak.api_key} directly in the view, but assign it to a variable in the controller, which you can then check for nil:

def some_action
  @account = Account.find_mak
  if @account.nil?
    # handle this case, i.e. a redirect to 404
  end
end  

Then in your view, you can use the variable and be certain it cannot be nil:

<%= form_tag "/apps/#{@accpunt.api_key}/users", #...

Upvotes: 2

Related Questions