protection level for model attributes in rails

橙三吉。 提交于 2019-12-11 13:05:54

问题


Suppose the following situation

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

  def password
    self[:password]
  end
end

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?


回答1:


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.

Here is a code example of how to overwrite the [] method:

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


来源:https://stackoverflow.com/questions/18023901/protection-level-for-model-attributes-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!