ID + Slug name in URL in Rails (like in StackOverflow)

前端 未结 6 1999
逝去的感伤
逝去的感伤 2020-12-28 08:29

I\'m trying to achieve URLs like this in Rails:

http://localhost/posts/1234/post-slug-name

with both ID and slug name instead of either

6条回答
  •  醉话见心
    2020-12-28 09:14

    Rails has some built-in support for SEO friendly URLs.

    You can create a url in the form: "id-title" by simply overriding the to_param method in your model.

    This is from one of my projects and creates a url with the id, category name and model name:

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

    Rails is smart enough to extract this back into the plain id when you access your controller action, so the following just works:

    def show
      @model = Model.find(params[:id])
      render :action => "show"
    end
    

提交回复
热议问题