接下來我們要美化網址,
要美化的主要是 show 的網址,
顯示出 id 其實會有點奇怪?
我們可以透過 Friendly_id 這個套件把 id 做成其他有意義的詞
gem 'friendly_id'
class AddSlugToProducts < ActiveRecord::Migration[7.0]
def change
add_column :drinks, :slug, :string
add_index :drinks, :slug, unique: true
add_column :desserts, :slug, :string
add_index :desserts, :slug, unique: true
end
end
這個指令會幫我們生出 friendly_id 的設定檔以及 migration
> rails g friendly_id
create db/migrate/20230924140957_create_friendly_id_slugs.rb
create config/initializers/friendly_id.rb
我們需要用到 FriendlyId 的方法,要擴充 model ,所以 extend FriendlyId
並且跟他說哪個欄位要當成 slug,我們剛多加了一個 slug 的欄位,
就把它拿來當 slug 吧
# app/models/drink.rb
class Drink < ApplicationRecord
extend FriendlyId
frinedly_id :slug, use: :slugged
...
end
# app/controllers/drink_controller.rb
class DrinksController < ApplicationController
...
def show
@drink = Drink.friendly.find(params[:id])
end
end
# app/components/drink_form_component.html.erb
<%= form_with model: [:admin, @dessert] do |f| %>
...
<div class="flex items-center mb-4 field">
<%= f.label :slug, 'slug' , class: 'mr-4' %><br />
<%= f.text_field :slug, class: 'rounded-md' %>
</div>
...
<% end %>
step 7. 在 controller 的 params 多加上 slug
# app/controllers/drink_controller.rb
def drink_params
params.require(:drink).permit(:name, :price, :description, :ingredient, :slug, :picture)
end
重新新增一筆,網址的 id 就會變成 slug 囉