The only way to ensure that the :name
matches the :id
is to compare them, and redirect if the value doesn't match what expected.
For example, you can add a before_action
in your controller, or enhance the one where you load the company
before_action :find_company
def find_company
@company = Company.find(params[:id])
# check and redirect
if @company.name != params[:name]
redirect_to(company_path(...))
end
end
Of course, the comparison has to be adjusted depending on how you generate the value for the :name
parameter.
Personally, I dislike the approach of having the id as query. I would probably prefer something like:
/companies/:id
and take advantage of the fact that any string with the format \d+-\w+
is translated into an integer in Ruby:
"12-company-name".to_i
=> 12
You can then have URLs like:
/companies/12-company-name
And simply use
Company.find(params[:id].to_i)
Of course, you will still need the before action if you want to redirect in case of name not matching the ID.
before_action :find_company
def find_company
id, name = params[:id].to_s.split("-", 2)
@company = Company.find(id)
# check and redirect
if @company.name != name
redirect_to(company_path(...))
end
end