我在开发 Rails 6 应用程序时遇到了这个挑战。
我有两种类型的用户:客户和管理员。我正在使用 Devise gem 进行身份验证。我希望 Customer 的 Products 视图不同于 Admins 视图。
我已经在 controllers 中有一个 app/controllers/admins 目录,用于 Admins 的 Devise 配置。
我是这样做的:
首先,使用admins 命名空间为管理员products 视图定义一个新的路由。
namespace :admins do
resources :products do
end
end
注意:这将影响管理员的路径/URL。比如说,products_path 不会是 admins_products_path。
然后,在 controllers 中将 products_controller.rb 添加到 app/controllers/admins 目录:
class Admins::ProductsController < ApplicationController
before_action :set_product, only: [:show, :edit, :update, :destroy]
# GET /products
# GET /products.json
def index
@products = Product.all
end
# GET /products/1
# GET /products/1.json
def show
end
# GET /products/new
def new
@product = Product.new
end
# GET /products/1/edit
def edit
end
# POST /products
# POST /products.json
def create
@product = Product.new(product_params)
respond_to do |format|
if @product.save
format.html { redirect_to admins_product_path(@product), notice: 'Product was successfully created.' }
format.json { render :show, status: :created, location: admins_product_path(@product) }
else
format.html { render :new }
format.json { render json: @product.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /products/1
# PATCH/PUT /products/1.json
def update
respond_to do |format|
if @product.update(product_params)
format.html { redirect_to admins_product_path(@product), notice: 'Product was successfully updated.' }
format.json { render :show, status: :ok, location: admins_product_path(@product) }
else
format.html { render :edit }
format.json { render json: @product.errors, status: :unprocessable_entity }
end
end
end
# DELETE /products/1
# DELETE /products/1.json
def destroy
@product.destroy
respond_to do |format|
format.html { redirect_to admins_products_url, notice: 'Product was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_product
@product = Product.find(params[:id])
end
# Only allow a list of trusted parameters through.
def product_params
params.require(:product).permit(:name, :sku, :short_description, :full_description)
end
end
注意:记下使用管理模块的 ProductsController 命名空间以及在 create、update 和 destroy 操作中修改的路径
最后,在 views 中,添加与 app/views/admins/products 目录中的 Admins Products 关联的视图。
注意:您可能需要修改视图中的路径以与管理员产品的路径相对应。例如,admins products 的 show 视图将是 admins_product_path(product) 而不是 product 或 product_path(product)。
使用cells gem 有一种更简洁的方法。这消除了重复代码的需要,当您需要为多达 3 个或更多角色定义视图时,它会派上用场。您可以在此处阅读有关如何使用它的更多信息:Object-Oriented Views in Rails。
就是这样。
我希望这会有所帮助