How to rewrite a header based URL?

This is a fairly open question, and I'm just looking for the best way.

Users can post links with headings. And I want my URL for SEO purposes to display these headers. In the same way, I believe stackoverflow works.

So, if the headline is "My foobar just made with my cat"

I would like the URL to be: www.website.com/posts/My-foobar-just-made-out-with-my-cat

Any ideas?

Thanks for that in advance!

+2
source share
2 answers

I used this in an old Rails 2.x application. Maybe the best approach to clear the name ...

(goes in your model)

 def to_param seo_uri end def seo_uri "#{self.id}-#{self.title.gsub(/[^a-z0-9]+/i, '-').gsub(/-{2}/, '-').gsub(/-$/, '')}" end 

Hope this helps!

UPDATE

Comments on this answer showed that for Rails 3 users there is a new method: #parameterize . The Rails API document for this method shows how to use it (cut-n-paste):

 class Person def to_param "#{id}-#{name.parameterize}" end end @person = Person.find(1) # => #<Person id: 1, name: "Donald E. Knuth"> <%= link_to(@person.name, person_path %> # => <a href="/person/1-donald-e-knuth">Donald E. Knuth</a> 
+2
source

There's a really awesome plugin, FriendlyId , that will handle all this for you. A load of truly smart features, including areas and handling 301 name redirections. This differs from the stackoverflow and Brian methods in that the identifier is not used in the URL.

+2
source

Source: https://habr.com/ru/post/1336988/


All Articles