如何使用设计 gem 在 rails 应用程序中停止 url 操作?

how to stop url manupulation in rails app with devise gem?

我正在使用设计 gem 来处理用户。用户与项目有 one_to_many 关联。并且有多个用户,每个用户都有自己的仪表板,但用户仍然能够在 url 中操作 project_id,并且能够看到其他用户的项目,也能够编辑删除它。我怎样才能阻止它?

登录后用户重定向(项目#index)-

project_controller.rb

def index
    @projects = current_user.projects.all.order("created_at DESC").paginate(page: params[:page], per_page: 15)
  end

  def show

    @project = Project.includes(stages: {tasks:}).find(params[:id])
    @stages = @project.stages
  end

  def new
    @project = current_user.projects.build
  end

  def create
    @project = current_user.projects.build(project_params)

    respond_to do |format|
      if @project.save
        format.html { redirect_to projects_url, notice: 'Project was successfully created.' }
        format.json { render :show, status: :created, location: @project }
      else
        format.html { render :new }
        format.json { render json: @project.errors, status: :unprocessable_entity }
      end
    end
  end

您可以简单地在 show 操作中使用 current_user.projects 范围:

def show
  @project = current_user.projects.includes(stages: :tasks).find(params[:id])
end

这样,如果您编辑 URL 并输入属于另一个用户的 ID,您将得到 ActiveRecord::RecordNotFound,默认情况下 Rails 将其作为 404 错误处理。

当然,您也可以使用这种方法来保护 editupdatedestroy 操作。