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

前端 未结 6 1998
逝去的感伤
逝去的感伤 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.

    0 讨论(0)
  • 2020-12-28 09:01

    I wrote a post about slugs in Rails 3. It provides pretty URL's and even more, secures your site from random scripts that ask for information just by increasing ID's. Also it avoids saving slugs in the database.

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-12-28 09:15

    You'll want to add a regular route with Route Globbing in addition to your resource route (assuming of course that's how your posts routes are defined). For example,

    map.resources :posts
    map.connect '/posts/:id/*slugs', :controller => 'posts', :action => 'show'
    
    0 讨论(0)
  • 2020-12-28 09:17

    the stringex gem contains ActsAsUrl to create URI-friendly representations of an attribute

    https://github.com/rsl/stringex

    It also contains a Unidecoder library, which can convert Unicode to ASCII.

    0 讨论(0)
  • 2020-12-28 09:26

    Use friendly_id. It has one nice feature: you can update your url without breaking the old one.

    Generating view url isn't working for me. I just added a small method in the model

    def to_param
      self.friendly_id
    end
    
    0 讨论(0)
提交回复
热议问题