Rails:当前用户应该只能查看自己的用户#show page(Devise)?

时间:2017-01-10 20:26:57

标签: ruby-on-rails

有没有办法让用户只能查看自己的个人资料页面(用户#show)?因此,如果身份为 1 的人试图访问www.myapp.com/users/412 url,他会被重定向到根页面吗?他只能访问www.myapp.com/users/1

我正在使用设计,这是我尝试过的。但是,使用这个代码很奇怪,当前用户无法访问他自己的页面。

users_controller.rb

class UsersController < ApplicationController
  before_action :authenticate_user!
  before_action :only_see_own_page, only: [:show]

  def show
    #some ruby code here
  end

  private

  def only_see_own_page
    if current_user.id != params[:id]
      redirect_to root_path, notice: "Sorry, but you are only allowed to view your own profile page."
    end
  end
 end

**的routes.rb *

resources :users, only: [:show]

1 个答案:

答案 0 :(得分:1)

唉,就这么简单......这对我有用:

def only_see_own_page
  @user = User.find(params[:id])

  if current_user != @user
    redirect_to root_path, notice: "Sorry, but you are only allowed to view your own profile page."
  end
end