Last Updated: February 25, 2016
·
2.181K
· rebyn

Friendly URLs in Rails

Bored with yoursite.com/articles/1</code> default URLs in Rails? Want something like yoursite.com/articles/obama-re-elected</code>? Here's a workaround.

Note: Unicode applied. That means a title of obama-đắc-cử</code> will have the result as /articles/obama-dac-cu</code>.

1. Put this in your Gemfile</code>:

gem "stringex", "~> 1.4.0"

2. Put this in your Model.rb</code>:

acts_as_url :name, url_attribute: :slug
def to_param
  slug
end

This will convert your :name attribute in your model to a friendly URL and put it into :slug

At the very beginning of your Model.rb</code>, put this if you're using Unicode titles:

# encoding: UTF-8

3. Then we need to migrate :slug into our current model

rails g migration AddSlugToModel slug:string
rake db:migrate

4. In your controller, replace: Model.find(params[:id])</code> with Model.findbyslug(params[:id])</code>

Active Admin compatible

to_param will override the setting of Active Admin, so you may need to add this tweak to your app/admin/YourModel.rb</code>:

around_filter do |controller, action|
    MyModel.class_eval do
      alias :__active_admin_to_param :to_param
      def to_param() id.to_s end
    end

    begin
      action.call
    ensure
      MyModel.class_eval do
        alias :to_param :__active_admin_to_param
      end
    end
  end

Remember to replace MyModel with your model name.

  • Tu qio.me/rebyn

PS: I know, Markdown in Coderwall sucks.

1 Response
Add your response

Thanks! You ActiveAdmin compatibility fix works like a charm!

over 1 year ago ·