Hi all,
I’m working on a Rails application. In this application I retrieve a
list of
‘brands’ using a method somewhere defined in my controller:
private
def get_brands
@brands = Product.find_by_sql(“select distinct brand from
products”);
end
However, I display this information in a listbox in the template for my
controller.
This means @brands should be available on each request.
In Java I would accomplish this by putting the @brands reference on the
session scope.
What is an effective way to do this in Ruby?
Regards,
Harm
On Dec 15, 2005, at 11:38 AM, Harm de Laat wrote:
Harm
Harm-
The easiest way is to use a before filter. If you need @brands to be
set in every controller in your app then put the follwing in
application.rb, but if you only need it in one controller then do it
in there:
class ApplicationController < ActionController::Base
attr_reader :brands
before_filter :get_brands
private
def get_brands
@brands = Product.find_by_sql(“select distinct brand from
products”);
end
end
That will make @brands available in any controller in your app. If
you only need it in one just put the same code in that particular
controller.
Cheers-
-Ezra Z.
Yakima Herald-Republic
WebMaster
http://yakimaherald.com
509-577-7732
[email protected]
Great!, Thanks this worked for me!
If you do ||= instead of =, it won’t re-run the query if the @brands
instance variable has already been set.
If your brands list doesn’t change much, it could save you some
duplicate requests.