Accessing the session in a model

Hi Nick,

Nick Brutyn wrote:

case @session[:language]

First thing to do is stop using '@session[]'. It's use has been depracated. Use 'session[]' instead. You'll have problems otherwise.

hth,
Bill

Avoid session use in the model. It’s ill advised and goes against MVC. You may someday want to use your models in a CRON job or an external process that does not require the web. Sessions are a controller piece.

Try this instead:

class Product < ActiveRecord::Base
attr_accessor :language
def name
case self.language
when “nl”
return self.name_nl

            when "en"
                    return self.name_en
            when "fr"
                    return self.name_fr
            end
    end

end

@product = Product.find 1
@product.language = session[:language]
@product.name

if @product.language = session[:language] gets to be too cumbersome to type, wrap it in a method you call

In application.rb add this:

finds the product and sets the language type based on session contents

product id defaults to params[:id] if no product id is provided.

def get_product(id = params[:id])

product = Product.find 1

product.language = session[:language]
product
end

Now you just do

def show
@product = get_product
end

This gets more complicated in collections though

@products = Product.find
:all
@products.each do |product|
product.language = session[:language]
end

But you could wrap that too.

Hope that helps you out. Looks like you’re doing internationalization. You might look into some plugins for that. I’ve not dealt with that yet but I know others are. Why not ask the list for some advice on the problem you’re trying to solve as well… I know others would be interested in the response.

Have a nice day!