Rails授权编辑和正确的用户

时间:2016-06-29 18:08:30

标签: ruby-on-rails ruby

我希望有正确的用户,管理员和编辑者能够编辑,更新和删除博客。

我的博客控制器中有这个:

before_action :require_user, only: [:new, :create, :edit, :update, :destroy]
before_action :correct_user, only: [:edit, :update, :destroy, :can_edit_blog?]

这是私下的:

    def can_edit_blog?
      true if ((current_user.admin? || current_user.editor?) || correct_user)
    end

    def correct_user
      @blog = current_user.blogs.find_by(id: params[:id])
      redirect_to root_url if @blog.nil?
    end

现在它只允许正确的用户,但不允许管理员或编辑者。我尝试过使用另一个before_action:admin_user,但这似乎没有用。

3 个答案:

答案 0 :(得分:1)

    before_action :require_creator, only: [:edit, :update, :destroy]

    ...

    def can_edit_blog?
        current_user.admin? || current_user.editor?
    end

    def require_creator
        @blog = Blog.find(params[:id])
        redirect_to root_url unless (current_user == @blog.user || can_edit_blog?)
    end

答案 1 :(得分:0)

我有一个具有类似逻辑的应用程序。这是我的控制器代码的样子。可以将一些私有方法抽象为ApplicationController。

before_action :require_user, only: [:new, :create, :edit, :update, :destroy]
before_action :require_creator, only: [:edit, :update, :destroy]

private

  def require_user
    access_denied unless logged_in?
  end

  def logged_in?
    !!current_user
  end

  def current_user
    @current_user ||= User.find(session[:user_id]) if session[:user_id]
  end

  def access_denied
    redirect_to root_path
  end

  def require_creator
    access_denied unless logged_in? and (current_user == @blog.user || current_user.admin?)
  end

答案 2 :(得分:0)

您不想在can_edit_blog来电:only的{​​{1}}选项中致电before_action。您想在correct_user中致电can_edit_blog?

correct_user

OP的解决方案是正确的,我的不是,请参阅他们更新的问题