How does Stack Overflow generate its SEO-friendly URLs?

后端 未结 21 1845
-上瘾入骨i
-上瘾入骨i 2020-11-22 04:27

What is a good complete regular expression or some other process that would take the title:

How do you change a title to be part of the URL like Stack

21条回答
  •  一向
    一向 (楼主)
    2020-11-22 05:00

    Assuming that your model class has a title attribute, you can simply override the to_param method within the model, like this:

    def to_param
      title.downcase.gsub(/ /, '-')
    end
    

    This Railscast episode has all the details. You can also ensure that the title only contains valid characters using this:

    validates_format_of :title, :with => /^[a-z0-9-]+$/,
                        :message => 'can only contain letters, numbers and hyphens'
    

提交回复
热议问题