无法访问 ActiveRecord 中的属性
Cannot access attribute in ActiveRecord
我想将 CanCanCan 引入我的 Rails 应用程序,但我未能读取我的用户类的角色属性。
我只需要一个 "one role per user" 解决方案,所以我在我的用户模型中添加了一列 'role' 并成功迁移了它,但是当我尝试读取该属性时,它为 nil...
我在我的用户类中创建了以下内容:
class User < ActiveRecord::Base
## User Model
ROLES = %i[admin default]
...
attr_accessor :role
...
end
当我在 Rails 控制台上尝试以下操作时:
irb(main):001:0> user = User.find(1)
User Load (1.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = LIMIT 1 [["id", 1]]
=> #<User id: 1, username: "ofhouse", email: "test@example.com", ... , role: "admin">
irb(main):002:0> user.role
=> nil
irb(main):003:0> user.username
=> "ofhouse"
我的用户角色为nil,而其他属性可以访问?
去掉role
的attr_accessor
,屏蔽AR自动生成的role
属性
我想将 CanCanCan 引入我的 Rails 应用程序,但我未能读取我的用户类的角色属性。 我只需要一个 "one role per user" 解决方案,所以我在我的用户模型中添加了一列 'role' 并成功迁移了它,但是当我尝试读取该属性时,它为 nil...
我在我的用户类中创建了以下内容:
class User < ActiveRecord::Base
## User Model
ROLES = %i[admin default]
...
attr_accessor :role
...
end
当我在 Rails 控制台上尝试以下操作时:
irb(main):001:0> user = User.find(1)
User Load (1.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = LIMIT 1 [["id", 1]]
=> #<User id: 1, username: "ofhouse", email: "test@example.com", ... , role: "admin">
irb(main):002:0> user.role
=> nil
irb(main):003:0> user.username
=> "ofhouse"
我的用户角色为nil,而其他属性可以访问?
去掉role
的attr_accessor
,屏蔽AR自动生成的role
属性