Rails 4:如何禁用Edit,Destroy等,

我可以在Rails中禁用“编辑”和“命令”吗?例如,如果我想为每个人禁用“编辑”,我在test_controller.rb中执行的操作是什么? 或其他什么? 我是Rails的新手,提前谢谢!

class BooksController < ApplicationController before_action :set_book, only: [:show, :edit, :update,:destroy ] # GET /books # GET /books.json def index @books = Book.all end # GET /books/1 # GET /books/1.json def show end # GET /books/new def new @book = Book.new end # GET /books/1/edit def edit end # POST /books # POST /books.json def create @book = Book.new(book_params) respond_to do |format| if @book.save format.html { redirect_to @book, notice: 'Book was successfully created.' } format.json { render :show, status: :created, location: @book } else format.html { render :new } format.json { render json: @book.errors, status: :unprocessable_entity } end end end # PATCH/PUT /books/1 # PATCH/PUT /books/1.json def update respond_to do |format| if @book.update(book_params) format.html { redirect_to @book, notice: 'Book was successfully updated.' } format.json { render :show, status: :ok, location: @book } else format.html { render :edit } format.json { render json: @book.errors, status: :unprocessable_entity } end end end # DELETE /books/1 # DELETE /books/1.json def destroy @book.destroy respond_to do |format| format.html { redirect_to books_url, notice: 'Book was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_book @book = Book.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def book_params params.require(:book).permit(:name, :author, :price) end end 

 `Rails.application.routes.draw do resources :books root :to => "home#index" get 'home/index' end` 

您可以限制其余路由以使editdestroy操作无法访问。

在您的routes.rb中,

 resources :books, except: [:edit, :destroy] 

请参阅: http : //guides.rubyonrails.org/routing.html#restricting-the-routes-created


编辑

如果要保留RESTful路由(这样您就不必修改视图中的代码),可以在控制器中使用before_action来重定向用户。

 before_action :redirect_user, only: [:edit,:destroy] def redirect_user redirect_to root_path end 

当您希望根据某些条件限制对某些操作的访问时,通常会使用此方法。

例如,如果您只想要管理员编辑和删除书籍,则可以在redirect_user中设置条件,检查当前用户是否为admin,并重定向非管理员用户。

你应该看看cancancangem。 https://github.com/CanCanCommunity/cancancan

它是Ruby on Rails的授权库,它限制了允许给定用户访问的资源。 因此,您可以创建一个管理类,并且只允许管理员编辑和销毁。 它非常简单易用,适用于设计。