Search code examples
ruby-on-railscontrollernomethoderror

Rails NoMethodError in controller


this is in my controller

def results
#searches with tags
@pictures = Picture.all
@alltags = Tag.all
searchkey = params['my_input']
pList = []
listsize = 0
while listsize < @pictures.size
  pList[listsize] = 0
  listsize += 1
end
@alltags.each do |tag|
  if searchkey == tag.tagcontent
    pList[tag.picture.id-1] += 1
  end
end
@pictures.each do |picture|
  if searchkey == picture.name
    pList[picture.id-1] += 1
  end
end
@pictures = @pictures.sort {|pic1, pic2| pList[pic2.id-1] <=> pList[pic1.id - 1]}

end

this error comes when this is called

NoMethodError in SearchController#results

You have a nil object when you didn't expect it! You might have expected an instance of Array. The error occurred while evaluating nil.+ Rails.root: /Users/kevinmohamed/SnapSort/server

Application Trace | Framework Trace | Full Trace app/controllers/search_controller.rb:31:in block in results' app/controllers/search_controller.rb:29:ineach' app/controllers/search_controller.rb:29:in `results'

31 is pList[picture.id-1] += 1 , 29 is @pictures.each do |picture|, why is this error happening


Solution

  • pList is an array, indexed with 0, 1, 2, 3, 4...

    Your line

    pList[picture.id-1] += 1
    

    is likely to refer to an index which doesn't exist. For example, if pList has 50 members, it has indecies 0-49. If the id of the above picture is 7891, then it will try to find an index of 7890 which of course doesn't exist. This will return nil, and try to execute "nil += 1", which is where your error is coming from.

    Perhaps pList should be a Hash keyed by picture ids? Depends on what you're trying to accomplish. But whatever you're trying to do, there is almost certainly a less verbose way of expressing it in Ruby.