无法在 rails 中正确设置用户权限



我的应用程序允许任何人查看列表,但不允许删除或编辑 - 这工作正常,因为如果他们尝试这样做,他们会收到错误消息。抱歉,此房源属于其他人。

但是,当现有用户尝试编辑或删除他们创建的列表时,它应该转到编辑屏幕或显示删除消息,但它会给出相同的错误消息抱歉,此列表属于其他人。

PostController.rb

class PostsController < ApplicationController
  before_action :set_post, only: [:show, :edit, :update, :destroy]
  before_filter :authenticate_user!, only: [:new, :create, :edit, :update, :destroy]
  before_filter :check_user, only: [:edit, :update, :destroy]
  # GET /posts
  # GET /posts.json
  def index
    @posts = Post.all
  end
  # GET /posts/1
  # GET /posts/1.json
  def show
  end
  # GET /posts/new
  def new
    @post = Post.new
  end
  # GET /posts/1/edit
  def edit
  end
  # POST /posts
  # POST /posts.json
  def create
    @post = Post.new(post_params)
    @post.user_id = current_user.id

      if @post.save
        redirect_to @post, notice: 'Post was successfully created.' 
      else
        render action: 'new' 
      end
  end
  # PATCH/PUT /posts/1
  # PATCH/PUT /posts/1.json
  def update
      if @post.update(post_params)
        redirect_to @post, notice: 'Post was successfully updated.'
      else
       render action: 'edit' 
      end
  end
  # DELETE /posts/1
  # DELETE /posts/1.json
  def destroy
    @post.destroy
    redirect_to posts_url

  end
  private
    # Use callbacks to share common setup or constraints between actions.
    def set_post
      @post = Post.find(params[:id])
    end
    # Never trust parameters from the scary internet, only allow the white list through.
    def post_params
      params.require(:post).permit(:company, :contact, :email, :telephone, :website)
    end
    def check_user
      if current_user != @post.user_id
        redirect_to posts_url, alert: "Sorry, this contact belongs to someone else but you can view detalis by clicking on show"
      end
    end
end

用户.rb

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
  validates :name, presence: true
  has_many :listings, dependent: :destroy
end

后.rb

class Post < ActiveRecord::Base

    validates :company, :contact, :email, :telephone, :website, presence: true
    belongs_to :posts
end

你正在将current_user与中间人进行比较,@post.user_id,所以它总是假的。你想做current_user.id != @post.user_id.

你知道cancan吗? https://github.com/ryanb/cancan封装权限的所有逻辑非常棒,而且非常易于使用。

最后,您应该研究pry(https://github.com/pry/pry),它是我知道的最好的调试工具。

相关内容

  • 没有找到相关文章

最新更新