Rails中模型属性的保护级别 [英] protection level for model attributes in rails
问题描述
假设以下情况
class User < ActiveRecord::Base
private
def password= p
self[:password] = p
end
def password
self[:password]
end
end
如果有权访问Rails控制台的人可以做:
If anyone with access to the Rails console can do:
Loading development environment (Rails 4.0.0)
2.0.0p247 :001 > User
=> User(id: integer, name:string, password:string)
2.0.0p247 :002 > u = User.find(1)
=> #<User id: 1, name: "Jack", password: "da6c253ffe0975ca1ddd92865ff3d5f0">
2.0.0p247 :003 > u.password = "123"
NoMethodError: private method 'password' called for #<User:0xa9145b0>
2.0.0p247 :004 > u[:password] = "123"
=> "123"
2.0.0p247 :005 > u
=> #<User id: 1, name: "Jack", password: "123">
2.0.0p247 :005 > u.save
=> true
为什么会这样?如何封装关键字段?
Why does this happen? How can I encapsulate critical fields?
推荐答案
我猜想密码
在模型中是 attr_accessible
。当字段是 attr_accessible
时,Rails会自动让您读写该字段。您有一个专用密码方法,该方法会覆盖Rails的 password
和 password =
方法,但没有覆盖 []
和 [] =
方法。您可以覆盖 []
和 [] =
方法,也可以使用 password
不是 attr_accessible
。
I am guessing that password
is attr_accessible
in the model. When a field is attr_accessible
, Rails automatically lets you read and write to the field. You have a private password method that overwrites the Rails password
and password=
methods, but you did not overwrite the []
and []=
methods as well. You can either overwrite the []
and []=
methods or make it so password
is not attr_accessible
.
这是如何覆盖<$的代码示例c $ c> [] 方法:
class User < ActiveRecord::Base
def [](word)
puts "I am the master of: #{word}"
end
def []=(key, value)
puts "Fluffy monsters"
end
end
使用此修改后的代码, []
方法将返回:
With this revised code, here is what the []
method will return:
>> u[:password] = "123"
=> nil
# prints "Fluffy monsters" in the console
>> u[:password]
=> nil
# prints "I am the master of: password" in the console
这篇关于Rails中模型属性的保护级别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!