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 search开发者_JS百科key == 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:in
each'
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
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.
This error is occurring when something you are iterating over produced a nil when it wasn't expecting one. You have a lot of code in your controller. I would suggest moving some of this logic into a method of a model and write some tests for it, including raising of errors when tags or pictures are not available. Then you can rescue the error in the controller to display a more friendly error message.
精彩评论