rails中模型属性的保护级别

时间:2013-08-02 18:37:47

标签: ruby-on-rails ruby-on-rails-4 encapsulation

假设以下情况

class User < ActiveRecord::Base
  private
  def password= p
    self[:password] = p
  end

  def password
    self[:password]
  end
end

如果有权访问Rails控制台的人可以这样做:

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

为什么会这样?我如何封装关键字段?

1 个答案:

答案 0 :(得分:0)

我猜测模型中的passwordattr_accessible。当字段为attr_accessible时,Rails会自动让您读取和写入字段。您有一个私有密码方法可以覆盖Rails passwordpassword=方法,但您也没有覆盖[][]=方法。您可以覆盖[][]=方法,也可以将password设为attr_accessible

以下是如何覆盖[]方法的代码示例:

class User < ActiveRecord::Base
  def [](word)
    puts "I am the master of: #{word}"
  end

  def []=(key, value)
    puts "Fluffy monsters"
  end
end

使用此修订代码,[]方法将返回以下内容:

>> u[:password] = "123"
=> nil
# prints "Fluffy monsters" in the console

>> u[:password]
=> nil
# prints "I am the master of: password" in the console