0

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.

Cojones
  • 2,930
  • 4
  • 29
  • 41

2 Answers2

1

FriendlyID also supports Unique Slugs by Scope.

Because you haven't provided some information about your app I can't give you a exact explanation.

But I've created an explanation based on your url.

If I'm right than you have a Item and a User model. The Item model belongs to the User model and the User model has many Items.

Here is how I would solve this problem:

Models:

# User model
class User < ActiveRecord::Base
  extend FriendlyId
  has_many :items
  friendly_id :name, :use => :slugged
end

# Item model
class Item < ActiveRecord::base
  extend FriendlyId
  belongs_to :user
  friendly_id :name, :use => :scoped, :scope => :user
end

Controller:

class ItemsController < ApplicationController
  before_action :set_user, :set_item

  def show
    # Show your item ...
  end

  private

  def set_user
    User.friendly.find(params[:user_id])
  end

  def set_item
    @user.items.friendly.find(params[:item_id])
  end
end

Routes:

Rails.application.routes.draw do
  get ':user_id/:item_id' => 'items#show'
end

This is a minimal implementation without validation. I hope this helps.

Happy coding :)

Tobias
  • 4,523
  • 2
  • 20
  • 40
1
#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.

Richard Peck
  • 76,116
  • 9
  • 93
  • 147