How to safely use a param variable to execute an enum search

142 Views Asked by At

Consider a User model

# app/models/user.rb
class User
   enum status: [:sad, :bored, :happy]
end

In a controller, I want to receive params[:status] and return all users with that status

i.e.

# app/controllers/users_controller.rb
class UsersController << ApplicationController
   def index_status
      status = "#{params[:status]}"
      if User.statuses.include? status
         @status = status.to_sym
         @countries = User.send(@status)
      else
        redirect_to root_path, notice: 'Invalid status'
    end
end

This works fine, but Brakeman gives me a dangerous send - User controlled method execution warning for the line

@countries = User.send(@status)

Is there a way to do this that will not incur a warning from Brakeman.

2

There are 2 best solutions below

1
Schwern On

From the ActiveRecord::Enum docs...

Of course, you can also query them directly if the scopes don't fit your needs:

@countries = User.where(status: @status)

Note this:

status = "#{params[:status]}"

Is better written as a call to #to_s.

status = params[:status].to_s

But there's no need to stringify it at all.

status = params[:status]
0
Obromios On

Based on comment from @Justin, this happens because Brakeman does not understand enums. I have opened a new issue for Brakeman, and will update this answer when it is resolved.