0

I have a url in this format.

/companies/:name?id=company_id

So for example the ABC company, assuming the id is 1,has as url

/companies/ABC?id=1

If someone changes the id parameter value, the company with the new id is correcty loaded and its view is shown but the url keeps showing the previous company name. For example, having a second company DEF with id 2

/companies/ABC?id=2

Instead of

/companies/DEF?id=2

Is there a way to check that id change and reload the url with the correct company name?
Thank you guys.

loricelli
  • 33
  • 7

1 Answers1

0

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
Simone Carletti
  • 173,507
  • 49
  • 363
  • 364
  • I really don't know how the before_filter idea didn't came to me lol. Thank you, it solved my problem and i also discover that rails functionality. Thank you very much. – loricelli Dec 26 '16 at 19:08