【发布时间】:2015-07-31 15:09:19
【问题描述】:
在阅读Rails 4 in Action 时,我正在尝试实现自己的应用程序,因此它看起来与书中的不同。 本书对应的commit是Section 7.2.3: Only admins can create or delete projects
在我的例子中,管理员只能删除该项目(item对应书中的project。)。
我的仓库https://github.com/tenzan/shop 并部署了http://ichiba-demo.herokuapp.com/
我要应用的规则是:
- 普通用户(您可以使用
staff@example.com/password登录)可以执行除destroy操作之外的所有操作。 - 管理员 (
admin@example.com/password) 只能destroy。
意识到我有:
在admin/items_controller.rb:
class Admin::ItemsController < Admin::ApplicationController
def destroy
@item = Item.find(params[:id])
@item.destroy
flash[:notice] = 'Item has been deleted.'
redirect_to items_path
end
private
def item_params
params.require(:item).permit(:name, :quantity)
end
end
在controllers/items_controller.rb:
class ItemsController < ApplicationController
before_action :set_item, only: [:show, :edit, :update]
def index
@items = Item.all
end
def new
@item = Item.new
end
def create
@item = Item.new(item_params)
if @item.save
flash[:notice] = 'Item has been created.'
redirect_to @item
else
flash.now[:alert] = 'Item has not been created.'
render 'new'
end
end
def show
end
def edit
end
def update
if @item.update(item_params)
flash[:notice] = 'Item has been updated.'
redirect_to @item
else
flash.now[:alert] = 'Item has not been updated.'
render 'edit'
end
end
private
def set_item
@item = Item.find(params[:id])
rescue ActiveRecord::RecordNotFound
flash[:alert] = 'The item could not be found.'
redirect_to items_path
end
def item_params
params.require(:item).permit(:name, :quantity)
end
end
在routes.rb:
Rails.application.routes.draw do
namespace :admin do
root 'application#index'
resources :items, only: :destroy
end
devise_for :users
root 'items#index'
resources :items, only: [:index, :show, :edit, :update, :new, :create] do
resources :comments
end
end
问题:
- 我是否必须在
routes.rb中指定操作,因为我已经指定了谁可以在其相应的控制器中使用哪些操作?当我将它们从routes.rb中删除时,我没有注意到任何变化... - 当我在两个地方(即
routes.rb和controllers/items_controllers.rb)指定操作时,我是否违反了 DRY 概念?
如果您指出其他地方需要改进以符合最佳实践,我会很高兴。
PS:主题可能含糊不清,请随时修改。
【问题讨论】:
标签: ruby authentication devise dry ruby-on-rails-4.2