views:

242

answers:

2

I'm trying to create a simple helper module in rails, and I'm stumped on the following error message from my new person form (app/views/people/new.html.erb):

undefined method `sort' for 97:Fixnum

Extracted source (around line #17):

14:   <p>
15:         <% nations = { 'United States of America' => 'USA', 'Canada' => 'Canada', 'Mexico' => 'Mexico', 'United Kingdom' => 'UK' } %>
16:     <%= f.label :country %><br />
17:         <%= radio_buttons(:person, :country, nations) %>
18:         
19:   </p>
20:   <p>

radio_buttons is a helper module I have created for my view. Here it is (app/helpers/people_helper.rb):

module PeopleHelper 

def radio_buttons(model_name, target_property, button_source) 
  html='' 
  list = button_source.sort 
  list.each do |x| 
    html << radio_buttons(model_name, target_property, x[1]) 
    html << h(x[0]) 
    html << '<br />' 
  end 
  return html 
end 

end

The problem appears to be on the "list = button_source.sort", but I'm not sure why it says the method is undefined. I have been able to use it directly within my view code. Am I not able to use methods like this within helper modules? Do I need to include something?

Thanks for any help!

A: 

undefined method 'sort' for 97:Fixnum means that 97, an instance of Fixnum, does not have a sort method. For some reason, the parameter button_source in your method is coming in as an integer.

A quick fix would be to write list = Array(button_source).sort which will coerce button_source to an Array, because Arrays are the most common class that has the sort method. If button_source is already an Array, nothing will be changed.

Mark Rushakoff
This got me past the sort error, so thanks! However, now I'm getting a "stack level too deep" error. My recursion appears to be problematic.
Magicked
+1  A: 

In the line html << radio_buttons(model_name, target_property, x[1]) the method calls itself recursively. This time the third argument is no longer a hash, but x[1] which is a Fixnum. And since Finxums don't respond to sort you get the error.

sepp2k