Rails controller manually sanitize parameters

2.2k views Asked by At

Suppose my views need to pass some params that are absolutely not related to a model. What are the best ways to sanitize the input in the controller ?

Eg - Validate inclusion of a parameter in a string array : display_type param that sets whether search results are displayed on a map or in a list, as cards, etc., but only a few are defined and available - Validate the type/numericality of some parameter (eg params[:page] should be an integer or fallback to default page 0

Currently I'm using something like

def validate_xxx_param
  if ['map', 'card'].include?(params[:display_type))
    ...
  else
    ...
  end
end

But is there a cleaner/better OOP way of doing that ?

1

There are 1 answers

1
Alex Kojin On

You can move this validation to Service object

class ValidateXXXParam
  def initialize(param)
    @param = param
  end

  def call
    if ['map', 'card'].include?(@param)
      ...
    else
      ...
    end
  end
end

# call it in controller
ValidateXXXParam.new(params[:display_type]).call

This is a good way to keep your controller's code clean and dry.