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.


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


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

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]

Now you just do

def show
@product = get_product

This gets more complicated in collections though

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

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!