imderek
imderek

Reputation: 1316

Rails: "You have a nil object when you didn't expect it"

In my controller:

Article.author_ids_in(params[:filters][:author_ids])

This of course returns an error ("You have a nil object...") if those particular params have not been passed. Here is the model method:

def self.author_ids_in(filters)
  unless filters.nil?
    where(:author_id + filters)
  else
    scoped
  end
end

As you can see, I'm already prepared for a nil object, so how can I get Ruby to allow nil to be passed?

Upvotes: 0

Views: 1373

Answers (1)

andrewpthorp
andrewpthorp

Reputation: 5106

params[:filters] is most likely nil so it's raising an exception when you try to go into it to get [:author_ids]

Either check before you call the scope, or rescue the exception:

begin
  Article.author_ids_in(params[:filters][:author_ids])
rescue NoMethodError
  # do something else here
end

Upvotes: 3

Related Questions