QUESTION — I want to access these methods from views directly. When
I do <%= debug navbar.all_modules %> it fails. It cannot find the
navbar.
This will work fine only if you have navbar as an object of your Navbar model, confirm whether you have done the same.
As I observe that your method in model does not have anything related to specific object of the class, you can have it as a class method by defining it as self.all_modules. This can be directly used by Navbar.all_modules
Note: One should not use model methods in views directly. Use controller objects or helpers for the same.
And I am still getting
undefined local variable or method `navbar' for #<ActionView::Base:
0x4be1140>
Extracted source (around line #2):
1: <div id="content">
2: <%= debug navbar.all_modules %>
ok let me explain you in your code
following is your code
1:
2: <%= debug navbar.all_modules %>
now the navbar is undefined , please replace navbar to Navbar capital N that is your Model name
see in this line
class Navbar < ActiveRecord::Base
In the controller for the action you are testing, did you create an
instance of your Navbar class? You are defining a Navbar class, but a
class without an instance is fairly useless... Something like:
@navbar = Navbar.new
If so, then the view code as you had it:
<%= @navbar.all_modules %>
should have an instance of Navbar to work with. Your all_modules method
inside Navbar cons a little dubious though...
NavBar is a reference table whose content needs to be accessed in all
VIEWS.
This includes the application layout too.
Can you please guide which is the best way to model this??? + where to
initialize an instance?
If you want to initialise the Navbar instance somewhere that has to be
accessed by all views (or the layout), put it in the application
controller as a before_filter. For example:
class ApplicationController < ActionController::Base
# Some other stuff
before_filter :get_navbar
def get_navbar
@navbar = Navbar.new
end
# More stuff
end
Then in you view or layout you can access methods using the syntax as
outlined earlier: