I want to limit the parameters from url in rails

Asked 1 months ago, Updated 1 months ago, 3 views

How do I limit the values when setting parameters in rails?

:age with age and passing parameters.

get/user/list/:age/=>"user#list"

In this case, the :age condition is

  • Number
  • Up to 3 digits
  • Maximum value is 125 (for now)

Therefore, I would like to do something other than this, but how do I set it up?

ruby-on-rails

2022-09-30 14:25

1 Answers

If :constraints is used to write the following:

get"/users/list/:age"=>"users#list",:constraints=>{:age=>/\d{1,3}/}

If you want to specify a specific number, use a little ingenuity in the regular expression.

get"/users/list/:age"=>"users#list",:constraints=>{:age=>/\d{1,2}|1[01]\d|12[0-5]/}

Or use lambda to do the following:

get"/users/list/:age"=>"users#list",:constraints=>lambda {|req|
  age=req.env ["action_dispatch.request.path_parameters"] [:age]
  age=~/\A\d{1,3}\z/and age.to_i<=125
}

However, in routes.rb, I think it's easy for the controller to determine the range, leaving it to be "numeric."


2022-09-30 14:25

If you have any answers or tips


© 2022 OneMinuteCode. All rights reserved.