Rails: How to change the variable in Application Controller

1.1k Views Asked by At

In my application, I have Company, Division, Users.... Company - have many Divisions, Users - belongs to one or more Divisions.

When user login, the current_division is set to User.division[0] in the Application_controller. I want to implement a feature where user can switch between different divisions. Any ideas about how to implement this functionality.

How to change current_division in the Application_controller? This current_division is used by other controllers and models.

  Class Division < ActiveRecord:Base
    def self.current_div options={}
        if options[:division_id].nil?
        current_user.division[0] 
    else
       Division.find_by_id(options[:id])
    end

end

I call Division.current_div method when user choose a different division from dropdown

2

There are 2 best solutions below

4
On BEST ANSWER

You can move the method in ApplicationController and make it as helper method. Set session variable whenever you want to switch the division. You should store your division_id in session. Your current_division method should looks like:

  class ApplicationController < ActionController::Base
    ...
    ...

    private

    def current_division
      if session[:division_id]
        @current_division = Division.find_by_id(session[:division_id])
        session.delete(:division_id)
      else
        @current_division ||= current_user.application[0] # not sure what are you trying to do here
      end
    end

    helper_method :current_division
  end

You just need to call current_division and it will check if session[:division_id] exists and will update the division as needed. You just need to set session var when you want to switch and call current_division anytime anywhere.

2
On

You can have a dropdown on navbar where you can load all the divisions. select the current division on dropdown. Pass the current division parameter on url params. check the params in application controller and set the divison.

class ApplicationController < ActionController::Base
  before_filter :set_current_division

  def set_current_division
     @current_division = Division.find_by_name(params[:division_name])
  end

end