---
# System prepended metadata

title: 製造亂數網址

---

製造亂數網址
===
migration
```ruby=
def change
    add_column :orders, :friendly_id, :string
    add_index :orders, :friendly_id, :unique => true

    Order.find_each do |e|
      e.update( :friendly_id => SecureRandom.uuid )
    end
end
```

model
```ruby=
before_validation :generate_friendly_id, :on => :create

def to_param
    self.friendly_id
end

private
def generate_friendly_id
    self.friendly_id ||= SecureRandom.uuid
end
```

controller
```ruby=
Order.find(params[:id]) change_to Order.find_by_friendly_id!(params[:id])
```