Ruby on Rails: NoMethodError in Controller#action – Undefined method ‘each’
I set an instance variable by running the following query:
@some_list = Model.find_by_column_name(nil)
I tried to interate the content of @some_list and received the following error:
NoMethodError in Controller#action
Showing app/views/model/list.rhtml where line [line number] raised:
undefined method `each’ for #…
Apparently, I just need to add “_all_” in the query:
@some_list = Model.find_all_by_column_name(nil)
Easy solution, eh?
Update: I found the solution after I looked at the back-end SQL query.
Task Load (0.000354) SELECT * FROM table WHERE [some condition] LIMIT 1
After I added “_all_” in the statement, I finally get the right query.
Task Load (0.000332) SELECT * FROM table WHERE [some condition]
May 8th, 2008 at 4:02 pm
i can’t believe i missed that. Thanks for the post.
May 8th, 2008 at 11:32 pm
You’re welcome. It’s easy to fall into the trap hence I created this post.
January 3rd, 2009 at 8:07 pm
Thanks. This helped me to.
I was seeing a similar NoMethodError with
@examples = example.find(:first)
in the controller, which resulted
in the following SQL (see your web server console output):
SELECT * FROM `examples` LIMIT 1
Apparently the corresponding “each” method in my views/index.html.erb file
(below) doesn’t work on a single record.
% @examples.each do |c| %>
’show’ } %>
When I changed the contoller method to:
@examples = example.find(:all)
The LIMIT 1 was no longer in the SQL query:
SELECT * FROM `examples`
And “each” worked.
January 4th, 2009 at 4:28 am
You’re welcome.
I’m glad my post helped you.
I’m trying to post the problems and the solutions in this blog.