0

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
Pimmesz
  • 335
  • 2
  • 8
  • 29
  • 2
    I would suggest you set `@companies = []` so that you can always rely on having an array in your view. In the view I would check `if @companies.empty?` to see if anything is in it. I don't see the authorize step in the first branch of the if condition – 23tux May 03 '18 at 12:46
  • Yes if I uncomment authorize @companies I get the following: Pundit::AuthorizationNotPerformedError - UserselectionsController: – Pimmesz May 03 '18 at 12:49
  • 1
    I think there is a `skip_authorization` helper, see https://github.com/varvet/pundit – 23tux May 03 '18 at 12:50
  • Yes thats it!!!! Thank you!!! – Pimmesz May 03 '18 at 12:54

1 Answers1

2

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
Jagdeep Singh
  • 4,880
  • 2
  • 17
  • 22