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

前端 未结 6 2000
逝去的感伤
逝去的感伤 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:00

    I know the question is quite old but I think it still deserves some interest and none of the answers are up-to-date or provide a way to generate exactly what the OP was looking for (i.e. http://localhost/posts/1234/post-slug-name).

    In routes.rb

    get 'posts/:id/:slug', to: 'posts#show', as: 'slugged_post'
    

    Then in the views

    <%= link_to slugged_post_path(post, post.name.parameterize) %>
    

    You might want to define a slug method in your model to avoid calling parameterize in the views.

提交回复
热议问题