在后台定商品位置的gem

目标

使用gem来让管理员可以在后台更改商品的排列顺序

步骤

Step 1: 安装 acts_as_list

Gemfile

+ gem 'acts_as_list'

运行 bundle install

Step 2: 在product model中添加position栏位

运行 rails g migration AddPositionToProduct position:integer
rake db:migrate

app/models/product.rb

class Product < ApplicationRecord
   mount_uploader :image, ImageUploader
+  acts_as_list
end

Step 3: 在admin后台加入上移、下移按钮

app/views/admin/products/index.html.erb

<td>
    <%= link_to("Edit", edit_admin_product_path(product)) %>
+   <%= link_to("上移", move_up_admin_product_path(product), :method => :post) %>
+   <%= link_to("下移", move_down_admin_product_path(product), :method => :post) %>
</td>

Step 4: 实作上移、下移功能

修改routes

config/routes.rb

...(略)
namespace :admin do
-  resources :products
+  resources :products do
+    member do
+      post :move_up
+      post :move_down
+    end
+  end
...(略)

在 admin/products_controller中进行定义

app/controllers/admin/products_controller.rb

...(略)
  +def move_up
  +  @product = Product.find(params[:id])
  +  @product.move_higher
  +  redirect_to :back
  +end

  +def move_down
  +  @product = Product.find(params[:id])
  +  @product.move_lower
  +  redirect_to :back
  +end
...(略)

Step 5: 让商品按照position排序

app/controllers/products_controller.rb

def index
-  @products = Product.all
+  @products = Product.all.order("position ASC")
end
app/controllers/admin/products_controller.rb

def index
  @products = Product.all.order("position ASC")
end

重置数据库
rake db:drop
rake db:create
rake db:migrate
rake db:seed (后面seed档的撰写记得加上position)
重开rails server