Calling a controller method from a view raises NoMethodError
If you put a custom function in application.rb or another controller and then try to access it from your view, you'll get the "No Method Error" similar to following:
NoMethodError in Categories#list
Showing app/views/categories/list.rhtml where line #23 raised:
undefined method `create_permalink' for #<#
The solution is to place the function as a helper function in the app/helpers/categories_helper.rb or app/helpers/application_helper.rb file.
5 Comments:
Thanks for this info. I'm a Rails newb and couldn't figure out what I was doing wrong. :)
But now my controller can't access that method. Is there a place to put methods that are accessible from both the controller and the views?
What you would do is create a module in your lib folder. You can write your method in this file. Then make a hook method in this file like:
def self.included(base)
base.send :helper_method, :some_method
end
You can add more methods on by comma separating them. Then to gain access to this you just need to say include MyModule in your application.rb controller.
I had a method, we'll call it is_foo? that I added to my ApplicationController. When I tried to call that method in the view, it wouldn't work, much like you describe. I moved is_foo? method to my ApplicationHelper file and then added this line at the top of my ApplicationController file:
include ApplicationHelper
Now, is_foo? method is available both to my controller AND to views.
1. class ApplicationController
2.
3. helper_method :preivate_method
4.
5. #code...
6.
7. private
8. def preivate_method #changed name, CamelCase in method names is bad coding
9. #your code block
10. end
11. end
then you can call this method from both controller and views.
http://railsforum.com/viewtopic.php?id=23708 see this for more ref.
Post a Comment
<< Home