Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encode rails model id in URLs with base36

I’m trying to encode the model id for a rails app using base36 following the first answer here but I am unsure as to what I need to do.

Where do I put id.to_s(36)? Do I need to add a column to my database?

I’d like to have my URLs to be domain.com/user/rD4g35tQ instead of domain.com/user/3.

Ruby 1.9.3 Rails 3.2.16

Here is my show action in my controller:

  def show
    @user = User.find(params[:id])
  end

Edit: Here is my create action:

  def create
    @user = User.new(params[:user])
    if @user.save
      sign_in @user
      redirect_to @user
    else
      render 'new'
    end
  end
like image 635
Ronan Burke Avatar asked Dec 06 '25 06:12

Ronan Burke


1 Answers

to_param is for this. It is used by the routing to generate paths. By default it returns an object's id, but you can override it in a model to be anything you want:

class User < ActiveRecord::Base

  def to_param
    id.to_s(36)
  end

end

In controllers, params[:id] will now be the string you wanted, but you'll need to convert back to the real primary key:

def show
  @user = User.find(params[:id].to_i(36))
end
like image 156
Tim Peters Avatar answered Dec 09 '25 23:12

Tim Peters