ruby-on-railsmodel-view-controllerglobal-variablesapplicationcontroller

Rails: How to change the variable in Application Controller


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


Solution

  • 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.