如果我的用户具有某个角色,则无法在Rails中重定向

时间:2016-05-11 17:09:45

标签: ruby-on-rails ruby-on-rails-4 redirect roles

我正在使用Rails 4.2.3。我想为我的用户分配角色,所以我在app / model / users.rb文件中有这个...

class User < ActiveRecord::Base
  has_many :assignments
  has_many :roles, through: :assignments

  def role?(role)
    roles.any? { |r| r.name.underscore.to_sym == role }
  end

  def admin?
    role? "Admin"
  end
end

但是当我使用系统中唯一的用户登录时,我没有被重定向到管理页面(而是执行下面的“else”子句...

  def create
    user = User.from_omniauth(env["omniauth.auth"])
    session[:user_id] = user.id
    if user.admin?
      render 'admin/index'
    else
      redirect_to root_path
    end
end

我无法弄清楚为什么会这样。以下是我PostGres数据库中当前唯一的数据...

myproject=> select * FROM Assignments;
 id | user_id | role_id |         created_at         |         updated_at         
----+---------+---------+----------------------------+----------------------------
  4 |       8 |       1 | 2016-05-10 21:15:01.863456 | 2016-05-10 21:15:01.863456
(1 row)

myproject=> select * FROM users;
 id |   provider    |          uid          |     name      | oauth_token | oauth_expires_at |         created_at         |         updated_at         |          email          
----+---------------+-----------------------+---------------+-------------+------------------+----------------------------+----------------------------+-------------------------
  8 | google_oauth2 | 177611649021871409999 | Dave A        |             |                  | 2016-05-10 21:15:01.861259 | 2016-05-10 21:15:01.861259 | myemail@gmail.com
(1 row)

myproject=> select * FROM roles;
 id | name  |         created_at         |         updated_at         
----+-------+----------------------------+----------------------------
  1 | Admin | 2016-04-28 19:55:43.473016 | 2016-04-28 19:55:43.473016
  2 | User  | 2016-04-28 19:55:43.492222 | 2016-04-28 19:55:43.492222

1 个答案:

答案 0 :(得分:0)

您正在将字符串“Admin”传递给undefined,但在传递给role?的块中,您在符号上匹配。这应该有效:

roles.any?

通过此,您可以将def role?(role) roles.any? { |r| r.name.underscore.to_sym == role.to_s.underscore.to_sym } end "Admin""admin"传递给:admin