I have an if else statement in which I check whether certain companies have been selected before. If a list is empty I want to pass @companies = "Empty" so I can use it to render a different view. Pundit however requires to be given a company.
Is there a way to skip the authorize at a specific point in a method? In this case skip it at the comment #Skip authorize @companies here?
policy_scope(Company)
if params[:query].present?
if (Company.search_by_name_and_category(params[:query].capitalize) - @selected_companies).empty?
@companies = "Empty"
# Skip authorize @companies here
else
@companies = (Company.search_by_name_and_category(params[:query].capitalize) - @selected_companies)
@companies.each {|company| authorize company }
end
else
@companies = Company.all - @selected_companies
@companies.each {|company| authorize company }
end
Apart from skipping the authorization conditionally, i would do following changes to the code to reduce the queries and code lines:
policy_scope(Company)
@companies = params[:query].present? ?
Company.search_by_name_and_category(params[:query].capitalize) :
Company.all
@companies -= @selected_companies
if @companies.blank?
skip_authorization
else
@companies.each { |company| authorize company }
end