akshay1188
akshay1188

Reputation: 1667

checking valid number of parameters in url rails

I have an url which accepts two parameter.How do i check the number of parameters passed in the routes and discard the request if it contains more than two parameters.

http://localhost:3000/users?product=car&category=honda

I want to check the number of parameters passed.

Thanks in advance

Upvotes: 1

Views: 458

Answers (1)

shingara
shingara

Reputation: 46914

You can do that in you routes.rb with the constraint with a class to do it:

Create the class

class NbParametersConstraint
  def initialize(nb)
    @nb = nb
  end

  def matches?(request)
    request.params.length <= @nb
  end
end

And in your routes use it :

  match "/users" => "users#index",
    :constraints => NbParametersConstraint.new

After you can do that in your Controller by a filter

class UserController

  before_filter :max_params, :only => :index

  private

  def max_params
    render :status => 404 if params.size > 3
  end

end

Upvotes: 1

Related Questions