Sergey Sevastyanov
Sergey Sevastyanov

Reputation: 61

Rails accessing session data in model

My database contains data for multiple years (each table has a year column). Whenever users login they have to select a year to work with.

After login, all data accessed by the user is scoped to the selected year. The selected year is stored in the session variable and in the global variable.

I am using active_admin and active_admin_import, and I want to limit importing data only to the selected year.

I do this by adding a validation in my model. First, I tried to use the session variable but I realised that the model doesn't have access to the session; therefore, I ended up putting the selected year into a $year variable.

This was working in development, but after I pushed to the production the global variable is blank within the model, and my validation doesn't work.

From what I read I understand it is a bad idea to make session data accessible to the model. I can't think about a different solution. Any suggestions?

Additional info: As the main table can store multiple years, I import into a working table (which has the validation rule for one year), then copy data to the production table.

This way, if the import data has the wrong year or multiple years, the import fails and user gets an error message.

Upvotes: 2

Views: 6715

Answers (1)

Mark
Mark

Reputation: 6455

As you rightly say your session data isn't available in your model, just your controller (and maybe views - not sure).

Therefore the way around this is to call your model method from the controller, where the data is available, with your session data as an argument. Let's say you've got a method that sets one of the model's attributes to true or false depending on the session data:

apps/models/model.rb

def thing_to_do(session_data)
  # do something with your session data
end

Then in your controller action that you're currently hitting, for example the show action:

app/controllers/random_controller.rb

def show
  model.thing_to_do(session[:user_id])
end

This will call the model method 'thing_to_do' with the session variable as an argument. Obviously you can include as many session variables as needed

Upvotes: 3

Related Questions