Ruby on rails 我如何限制某人访问他没有的数据';没有创造?(红宝石)

Ruby on rails 我如何限制某人访问他没有的数据';没有创造?(红宝石),ruby-on-rails,ruby,devise,scaffold,Ruby On Rails,Ruby,Devise,Scaffold,我将RubyonRails与Desive一起使用。 我制作了一个脚手架 任务\u controller.rb: def index @tasks= current_user.tasks end 通过使用它,我可以向人们展示他们创造的东西, 但其他用户可以看到他们尚未输入的任务的数据,如: GET /tasks/1 GET /tasks/2 虽然id为1的任务不是由当前用户创建的,但用户可以访问该任务。尝试: def show @task = current_user.tasks.f

我将RubyonRails与Desive一起使用。 我制作了一个脚手架

任务\u controller.rb:

def index
   @tasks= current_user.tasks
end
通过使用它,我可以向人们展示他们创造的东西, 但其他用户可以看到他们尚未输入的任务的数据,如:

GET /tasks/1
GET /tasks/2
虽然id为1的任务不是由当前用户创建的,但用户可以访问该任务。

尝试:

def show
  @task = current_user.tasks.find(params[:id])
  # or with error handling
  # begin
  #   @task = current_user.tasks.find(params[:id])
  # rescue
  #   redirect_to [:tasks], flash: { error: 'not authorized' }
  #   return
  # end
end
对于这些案例,有Pundit gem()。您的代码将显示:

class TaskPolicy
  attr_reader :user, :task

  def initialize(user, task)
    @user = user
    @task = task
  end

  def show?
    user.tasks.include? task
  end
end
以及控制器的操作:

def show
  @task = Task.find(params[:id])
  authorize @task
  ...
end

此操作将引发Pundit::NotAuthorizedError,如果当前用户没有确定的任务

是,您可以使用筛选器限制此操作,例如

 class TasksController < ApplicationController
    before_filter :user_can_view_task, only: :show

    def show
       #you do not need to set @task here as it will be set by the filter method
    end

    private
       def user_can_view_task
          @task = Task.find(params[:id])
          unless @task.user_id == current_user.id
            flash[:notice] = "You may only view Tasks you have created."
            redirect_to(tasks_path)
          end 
       end
 end
class TasksController
每次用户点击show视图的路由时,它都会在渲染视图之前执行此方法。(因此“之前”)


此方法将查找任务并确定当前用户是否创建了任务(假设用户和任务之间存在关联)。如果用户不是任务创建者,它会将他们重定向回索引视图,并通知他们只能查看他们创建的任务,而不允许他们访问节目。

这还涉及到使用
@task进行不必要的数据库查询。user
@th3lazytig3r用户如何与任务关联?更新为使用
id
解决kardeiz问题。这很好,但是def显示了吗?user.tasks.include?任务它做什么?我想限制用户,比如如果你创建了一个任务,只有你才能查看它。而且我也找不到'error'的policy
TaskPolicy
。请帮助我@SergeiStralenia和顺便说一句,关于如何为权威人士撰写政策的任何参考资料,请attach@th3lazytig3r,你应该安装gempundit。然后调用“railsgpundit:install”。此脚本将在项目中创建应用程序/策略目录。然后创建task_policy.rb文件并插入我的任务策略代码。修改你的表演动作。最后在应用程序控制器中插入“包含权威”。一切都会好起来的。