ruby-on-railsruby-on-rails-4routesfriendly-id

How can I make a custom path for a model?


I'm using FriendlyID to make my URLs look nice, so what I got now is:

/items/my-personal-item

But what I would like is:

/user1/my-personal-item

Where user1 is the username of a user owning my-personal-item.


Solution

  • #config/routes.rb
    resources :users, path: "" do
       resources :items, path: "", only: [:show, :index] #-> url.com/:user_id/
    end
    

    FriendlyID has to reside in any model with which you're using, so if you wanted to use it on User as well as Item, you'd have to use the following setup:

    #app/models/user.rb
    class User < ActiveRecord::Base
      extend FriendlyId
      friendly_id :username
    end
    
    #app/models/item.rb
    class Item < ActiveRecord::Base
      extend FriendlyId
      friendly_id :title
    end
    

    This should give you the ability to call: url.com/user-name/my-personal-item

    --

    If you wanted to back it all up with the appropriate controller actions, you could use the following:

    #app/controllers/items_controller.rb
    class ItemsController < ApplicationController
       def show
         @user = User.find params[:user_id]
         @item = @user.items.find params[:id]
       end
    end
    

    As a pro-tip, you'll want to look at the friendly_id initializer to set some defaults for your app:

    #config/initializers/friendly_id.rb
    config.use :slugged #-> make sure this is valid
    config.use :finders #-> make sure this is valid
    

    By setting the above options, you'll just be able to call friendly_id [[attribute]] in your models.