[Rails] 建立簡易 Category 方式
說明
此範例主要建立簡易的分類與下拉選單,例如:商店有分中式、日式、韓式等類型可選擇,將建立兩table進行類別對商店的1對多關連。
建立方式
1. 先建立 Model Category 及 category_id 欄位
rails g model Category name:string content:text
rails g migration add_category_id_to_shop category_id:integer
rake db:migrate
2. 建立關聯
class Shop < ActiveRecord::Base
belongs_to :category
end
class Category < ActiveRecord::Base
has_many :shops
end
3. 建立新增/編輯時的分類選項
<%= f.input :category_id, collection: Category.all, label_method: :name, value_method: :id, label: "category", include_blank: "請選擇..." %>
記得補上strong parameters
def shop_params
params.require(:shop).permit(:category_id)
end
4. 建立分類資料
用seed或tasks或rails console建立
category = Category.create([
{ name: '中式菜餚' },
{ name: '日式料理' },
{ name: '韓式風味' }
])
5. 首頁的分類選單
<div class="list-group">
<% @categories.each do |category|%>
<%= link_to(category.name, shops_path(category: category),
class: "list-group-item #{"active" if current_page?(shops_path(category: category))}") %>
<% end %>
</div>
6. Contorller調整
def index
if params[:category].present?
@shops = Shop.where(category_id: params[:category])
else
@shops = Shop.all
end
end
參考
留言