0

i'm looking to fetch the collection from one model to display over the all pages.

Application.html.erb

 <ul>
    <% @category.each do |c| %>
   <li><%= c.name %></li></ul>
        <% end %>
        </ul>

Controller

 @categories = Category.all

how I fit it in the Application controller without having to copy and paste on all controllers?

dcalixto
  • 411
  • 1
  • 9
  • 26

2 Answers2

5

In your ApplicationController.rb create an before_filter and define it to call a specific method.

For example:

class ApplicationController < ActionController::Base
  before_filter :load_categories

  protected
  def load_categories
    @categories = Category.all
  end
end

Now, you should be able to access the @categories from all your views.

In your view:

<ul>
  <% @categories.each do |c| %>
  <li><%= c.name %></li></ul>
  <% end %>
</ul>

Hope it helps you.

Kleber S.
  • 8,110
  • 6
  • 43
  • 69
  • I don't believe you can set up instance variables in before filters. I've tried this and it didn't work. – cdesrosiers Jun 13 '12 at 02:24
  • yeah i tested the both methods and this did not worked for me as well – dcalixto Jun 13 '12 at 02:30
  • When I tried this, the variable was nil when used in the view. I remember reading an explanation as to why this is, but can't seem to find the article... – cdesrosiers Jun 13 '12 at 02:32
  • 1
    this is actually the best way to do it. Imagine in some controller action you want to only display a range of categories, you can just override the instance method in that action and it's done. Using the Model at the view there is no way to do this, only creating a new layout... – Ismael Abreu Jun 13 '12 at 03:02
  • I have a question, why a protected method and not private one? – Ismael Abreu Jun 13 '12 at 03:04
  • take a look at this [post](http://stackoverflow.com/questions/4495078/protected-and-private-methods-in-rails). It should answer that! ;) – Kleber S. Jun 13 '12 at 03:17
1

Just use

<ul>
<% Category.all.each do |c| %>
 <li><%= c.name %></li></ul>
<% end %>
 </ul>

You don't have to set up an instance variable in the controller.

cdesrosiers
  • 8,862
  • 2
  • 28
  • 33