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

时间:2014-04-04 15:00:07

标签: ruby-on-rails ruby ruby-on-rails-3

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

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

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

user.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

post.rb

class Post < ActiveRecord::Base


    validates :company, :contact, :email, :telephone, :website, presence: true

    belongs_to :posts
end

1 个答案:

答案 0 :(得分:1)

您正在将current_user与整数@post.user_id进行比较,因此它始终为假。你想做current_user.id != @post.user_id

你知道cancan吗? https://github.com/ryanb/cancan 很好地封装了所有权限逻辑,并且非常容易使用。

最后,您应该查看pryhttps://github.com/pry/pry),它是我知道调试的最佳工具。