Reputation: 607
I would like to create a generic method like the current_user
method provided by Devise which is usable on views and controllers. In my case, I want to know the current company.
My code :
class ApplicationController < ActionController::Base
before_action :set_company
protected
def set_company
@current_company =|| nil
if current_user.admin? && session[:company_id].present?
@current_company =|| Company.find(session[:company_id])
else
@current_company =|| current_user.company
end
end
end
Upvotes: 0
Views: 53
Reputation: 36860
What you've got almost does it... just add the method itself and make it a helper method so it's available in views.
class ApplicationController < ActionController::Base
helper_method :current_company
before_action :set_company
def current_company
@current_company
end
protected
def set_company
@current_company =|| nil
if current_user.admin? && session[:company_id].present?
@current_company =|| Company.find(session[:company_id])
else
@current_company =|| current_user.company
end
end
end
Upvotes: 1
Reputation: 2799
add the helper_method property, and make the method public
helper_method :set_company
this will make it available in every view in your application
Upvotes: 1