【发布时间】:2012-02-07 23:11:48
【问题描述】:
我想知道是否可以将属性键设为只读。这意味着它只能在创建对象时分配
更新:我希望能够使用 update_attributes 之类的东西,并且确保该方法只会更新可以被覆盖的密钥。例如,如果我有
class User
include MongoMapper::Document
key :firstName, String, :required => true
key :lastName, String, :required => true
key :username, String, :required => true, :unique => true, :readonly => true
key :password, String, :required => true
end
(只读验证是伪代码,我希望存在这样的东西)
那么我希望下面的代码会引发错误或失败
user = User.find_by_username("foo")
user.update_attributes({:username => "bar"})
puts "You cannot change the username" unless user.valid?
我也想要这样的东西,但是是另外一回事
user.update_attributes({:unwantedKey => "fail!"})
puts "You cannot add keys that are not in the User scheme" unless user.valid?
【问题讨论】:
-
作为程序员的你有责任在分配或不分配某些东西时负责。还是您的意思是您想避免通过参数更改密钥?然后你可以使用
attr_accessbile :key_x -
@three 我用一个例子更新了这个问题。
-
@GuidoMB 我很困惑为什么你想要你所要求的行为。对于您要解决的任何问题,这听起来像是错误的解决方案。你能提供更多动力吗?
-
@PlasticChicken 我在用户实体上使用 Sinatra 公开 CRUD 操作。在更新方法中,API 的使用者不能对用户实体进行任何更新,除了用户名字段。这就是我使用 update_attributes 方法的原因,因为我不想手动更新每个更改。但我不想更改用户名字段
标签: ruby mongodb mongomapper