参考https://blog.skcript.com/implementing-categories-in-ruby-on-rails-14c2b5e77b34#.ugsdz8w8b
参考http://taomengdi99.logdown.com/posts/1420713
近日做了一个商品购物网站(https://github.com/AnattaGuo/jdstore2),想给admin账户添加商品分类功能。
-
在命令端输入
rails g scaffold category name:string desc:text
在命令端输入
rake db:migrate
-
在命令端输入
rails generate migration AddColumnsToProducts category_id
,然后输入rake db:migrate
建立product model和category model的relationship. 修改如下两个文件:
#app/models/product.rb
belongs_to :category
#app/models/category.rb
has_many :products
@categories = Category.all.map{|c| [ c.name, c.id ] }
, 给product_params添加:category_id
:
#app/controllers/admin/products_controller.rb
class Admin::ProductsController < ApplicationController
layout "admin"
before_action :authenticate_user!
before_action :admin_required
def index
if params[:category].blank?
@products = Product.all
else
@category_id = Category.find_by(name: params[:category]).id
@products = Product.where(:category_id => @category_id)
end
end
def new
@product = Product.new
@categories = Category.all.map{|c| [ c.name, c.id ] }
end
def edit
@product = Product.find(params[:id])
@categories = Category.all.map{|c| [ c.name, c.id ] }
end
def update
@product = Product.find(params[:id])
@product.category_id = params[:category_id]
if @product.update(product_params)
redirect_to admin_products_path
else
render :edit
end
end
def create
@product = Product.new(product_params)
@product.category_id = params[:category_id]
if @product.save
redirect_to admin_products_path
else
render :new
end
end
private
def product_params
params.require(:product).permit(:title, :description, :quantity, :price, :image, :category_id)
end
end
app/views/admin/products/edit.html.erb
和app/views/admin/products/new.html.erb
两个文件里添加以下代码:
<%= select_tag(:category_id, options_for_select(@categories), :prompt => 'Select one!') %>
app/views/layouts/admin.html.erb
里添加如下代码:这样在http://localhost:3000/admin/products 下面就可看到catetory了
最终分类成果演示: