1

I have the record's ID and name in the URL.

def to_param
    "#{id} #{name}".parameterize
end

But any name works in the URL. I can do the following and it works

www.site.com/records/ID-anything-here-works

How can I redirect ID-anything to ID-name?

Here is an example.

Let's say I have a "product" model and a record with the name "shoe" and an id "6".

The url looks like this

products/6-shoe

But this URL also works

products/6-eiufwojfeowjfowef

How can I make it so the second URL redirects to the first?

I'm working with the show action:

def show
    @website = Website.find(params[:id])
end
19
  • I don't understand your question. can you please rephrase it? Commented Jan 29, 2017 at 10:21
  • Ok i think i understand what you mean: you want them to only enter a name which is current available in the database? Commented Jan 29, 2017 at 10:22
  • The record name and record ID are in the database. I want the ID and name to be in the URL and I have this working currently. But the record seems to be retrieved by the ID only, I can type in anything I want for the name in the URL and it displays the record. I want it to redirect to ID-name. Commented Jan 29, 2017 at 10:29
  • have you overriden with to_param in your model? Commented Jan 29, 2017 at 10:30
  • I don't know what you mean by "overridden" - maybe I have, maybe I haven't, I'm not sure. But in the question, I showed the def_param snippet I have in my model. Commented Jan 29, 2017 at 10:32

1 Answer 1

1

Try this:

  def show
    @website = Website.find(params[:id])
    unless params[:id] == @website.to_param
      redirect_to @website, status: 301
    end
  end

It finds the instance as it is doing now (negligent of the name), but then it redirects a user to a correct path with current name.

Note the 301 status in redirect, this is good for SEO, you will have only one actual URL for each website.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.