How do I rewrite URL's based on title?

前端 未结 2 1689
臣服心动
臣服心动 2021-01-15 05:27

This is a fairly open-ended question, and I\'m just looking for the best possible avenue.

Users can post links with titles. And I want my URL\'s for SEO purposes to

2条回答
  •  萌比男神i
    2021-01-15 06:13

    I used this in an old Rails 2.x app. There may be a better approach to scrubbing the title...

    (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 indicated there is a new method available for Rails 3 users: #parameterize. The Rails API document for this method shows how it should be used (cut-n-paste):

    class Person
      def to_param
        "#{id}-#{name.parameterize}"
      end
    end
    
    @person = Person.find(1)
    # => #
    
    <%= link_to(@person.name, person_path %>
    # => Donald E. Knuth
    

提交回复
热议问题