Rolify Table Error(user.add_role:admin Unknown Key Error)

时间:2016-03-22 01:50:05

标签: ruby-on-rails devise key cancancan rolify

我试图设置rolify gem,但我遇到了在控制台中为用户分配角色的问题。

这是我的错误:

2.2.1 :007 > user.add_role :admin
ArgumentError: Unknown key: :optional.

我用cancancan和rolify运行设计。我还运行Koudoku gem以获得订阅付款支持。我怀疑这个错误可能是因为我的"订阅"表还有一个" user_id"柱。我有什么办法可以解决这个问题吗?

这是我的架构。

create_table "subscriptions", force: :cascade do |t|
t.string   "stripe_id"
t.integer  "plan_id"
t.string   "last_four"
t.integer  "coupon_id"
t.string   "card_type"
t.float    "current_price"
t.integer  "user_id"
t.datetime "created_at",    null: false
t.datetime "updated_at",    null: false
end

create_table "users", force: :cascade do |t|
t.string   "email",                  default: "", null: false
t.string   "encrypted_password",     default: "", null: false
t.string   "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer  "sign_in_count",          default: 0,  null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string   "current_sign_in_ip"
t.string   "last_sign_in_ip"
t.datetime "created_at",                          null: false
t.datetime "updated_at",                          null: false
t.string   "first_name"
t.string   "string"
t.string   "last_name"
end

 add_index "users", ["email"], name: "index_users_on_email", unique: true
 add_index "users", ["reset_password_token"], name:    
 "index_users_on_reset_password_token", unique: true

create_table "users_roles", id: false, force: :cascade do |t|
t.integer "user_id"
t.integer "role_id"
end

add_index "users_roles", ["user_id", "role_id"], name:   "index_users_roles_on_user_id_and_role_id"

end

感谢。

1 个答案:

答案 0 :(得分:39)

Rolify角色生成器使用以下代码生成角色模型:

class Role < ActiveRecord::Base


has_and_belongs_to_many :users, :join_table => :users_roles

  belongs_to :resource,
             :polymorphic => true,
             :optional => true

  validates :resource_type,
            :inclusion => { :in => Rolify.resource_types },
            :allow_nil => true

  scopify
end

Rails版本5及更高版本支持:optional => true参数。要解决此问题,只需从您的角色模型中删除该行,您应该好好去。以下是最终代码供您参考:

class Role < ActiveRecord::Base
  has_and_belongs_to_many :users, :join_table => :users_roles

  belongs_to :resource,
             :polymorphic => true

  validates :resource_type,
            :inclusion => { :in => Rolify.resource_types },
            :allow_nil => true

  scopify
end