How to overwrite url's get parameter

Asked 2 years ago, Updated 2 years ago, 38 views

Ruby on rails is creating a simple list page.
For paging purposes, I have passed the get parameter offset and limit at the URL.
If the parameter is blank or string on the controller, the default value is "0", but
I think it's a little unnatural because the URL remains the same.
For example, if 0.0.0.0:3000/admin/history?offset='a'&limit=20,
In the controller, "0" is put in offset so that the id is taken out of the data with "0".
However, the URL is the mom above, so I will send the URL
0.0.0.0:3000/admin/history?offset=0&limit=20
I would like to overwrite it as above.

Here's my controller code.

def index
  @offset=offset
  @limit=limit

  @history=history.limit(@limit).offset(@offset))
end

offset
  return 0 if params[:offset].nil?
  return 0 unless param[:offset]=~/^[0-9]*$/
end

def limit
  return 10 if params[:limit].nil?
  return 10 unless param[:limit]=~/^[0-9]*$/
end

ruby-on-rails ruby

2022-09-30 11:27

1 Answers

The (GET) parameters included in the URL are input values from the user, as the name is given, and I think it is difficult to change them in one request.

Why don't you cut the redirect and take care of it?

DEFAULT_OFSET_PARAM=0
DEFAULT_LIMIT_PARAM = 0

before_action:validate_offset, only::index
before_action:validate_limit, only::index

def index
  # ...
end

def valid_number ?(num)
  return false if num.nil?
  return false unless num=~/^[0-9]*$/
  true
end

default_offset
  unless valid_number ? (params[:offset])
    redirect_to history_path (offset:DEFAULT_OFSET_PARAM, limit:params[:limit])
  end
end

def validate_limit
  unless valid_number ? (params[:limit])
    redirect_to history_path(offset:params[:offset], limit:DEFAULT_LIMIT_PARAM)
  end
end


2022-09-30 11:27

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.