添加分类功能 Category for Ruby On Rails app

参考https://blog.skcript.com/implementing-categories-in-ruby-on-rails-14c2b5e77b34#.ugsdz8w8b
参考http://taomengdi99.logdown.com/posts/1420713

近日做了一个商品购物网站(https://github.com/AnattaGuo/jdstore2),想给admin账户添加商品分类功能。

  1. 在命令端输入rails g scaffold category name:string desc:text

    Snip20170305_20.png

  2. 在命令端输入rake db:migrate

  3. 在命令端输入rails generate migration AddColumnsToProducts category_id,然后输入rake db:migrate

    Snip20170305_22.png

  4. 建立product model和category model的relationship. 修改如下两个文件:

#app/models/product.rb
belongs_to :category
Snip20170305_25.png
#app/models/category.rb
has_many :products

Snip20170305_26.png
5. 在admin::products#controller文件里给new、edit、update、create添加代码@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
Snip20170305_33.png

Snip20170305_35.png
6. 在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!') %>

Snip20170305_29.png
7. 去http://localhost:3000/categories 新建类别
new category.gif
8. 将category的选项呈现在admin的页面上。在app/views/layouts/admin.html.erb里添加如下代码:

这样在http://localhost:3000/admin/products 下面就可看到catetory了

Snip20170305_38.png

最终分类成果演示:


new category-new product.gif
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容