Search code examples
ruby-on-railsrubypretty-urls

how to use slug for only certain links in rails


I use a slug instead of an ID in my rails app to prettify the url when viewing a post.

Therefore in my articles.rb file I currently use this for all links:

 def to_param
    slug
  end

This results in a url like: ...articles/this-is-a-test-article

I now want to use the normal id url format only when editing a post, is there a way to modify this to allow me to do that?

i.e. ...articles/7

For reference, in my articles controller I have:

def edit
@article = Article.find_by_slug(params[:id])
end

Any help will be much appreciated, thanks.


Solution

  • friendly_id

    You'll be much better using friendly_id

    This works exactly how you need (you have the slug column already, and you'll need to do this):

    #app/models/article.rb
    Class Article < ActiveRecord::Base
        friendly_id :slug, use: [:slugged, :finders]
    end
    

    --

    .find

    The reason why friendly_id will be good is it has adapted the find method of Rails to handle both slugs & id's:

    #app/controllers/articles_controller.rb
    def [action]
        @article = Article.find params[:id]
    end
    

    This means you can do this:

    article_path(@article) #-> can have either id or slug attributes present
    

    This will populate the :id param with either the id or slug, depending on which is present, allowing you to call the find method in the controller for either.