Search code examples
ruby-on-railsrubyurlslug

Creating a slug in rails without defining it in the model


I want to create a friendly URL in rails by overiding the to_params method:

 def to_param
     "#{id}-#{brand}-#{name}"
 end 

But what if I am calling the object from another controller. For example, if I have a Site controller and a Product controller... I want to create an action in the Site controller that displays the product rather than using the show action in the Products controller.

How would I accomplish this?


Solution

  • You should use an already existent gem for this case. The friendly_id gem provides the functionality you are looking for. Check their guide for more information about to setup and use.

    For a simple example, as taken from here:

    in your model:

    class Post < ActiveRecord::Base
      attr_accessible :content, :title
    
      extend FriendlyId
      friendly_id :title, use: :slugged
    end
    

    then create a migration:

    $ rails g migration add_slug_to_posts slug:string
    $ rake db:migrate
    

    and fill it:

    class AddSlugToPosts < ActiveRecord::Migration
      def change
        add_column :posts, :slug, :string
        add_index :posts, :slug
      end
    end