Forum: Ruby on Rails session scope?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Harm de Laat (Guest)
on 2005-12-15 21:40
(Received via mailing list)
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
Ezra Z. (Guest)
on 2005-12-15 22:01
(Received via mailing list)
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
removed_email_address@domain.invalid
Harm de Laat (Guest)
on 2005-12-15 22:07
(Received via mailing list)
Great!, Thanks this worked for me!
Wilson B. (Guest)
on 2005-12-16 01:04
(Received via mailing list)
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.
This topic is locked and can not be replied to.