MongoMapper 的只读属性/键
我想知道是否有办法使属性键只读。这意味着它只能在创建对象时分配
UPDATE:我希望能够使用 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我会重新审视您的要求,您需要通过验证来完成此操作,而不是使用自定义控制器过滤或 attr_accessible 来控制 可访问性。
如果验证确实是正确的解决方案,请自行推出三个建议是个好主意,这里有一些身份映射安全代码来检查数据库:
但是要小心! MongoMapper 不存储值为
nil
的键。这将破坏上面的only_existing_keys
方法,因此您可能必须在某处存储有效密钥的数组。希望这是一个足够的起点。
I would revisit your requirement that you need to do this with validations rather than using custom controller filtering or
attr_accessible
to control accessibilty.If validations really are the correct solution, rolling your own like three suggests is a good idea, here's some identity-map-safe code to check against the database:
But watch out! MongoMapper does not store keys whose value is
nil
. That's going to foil theonly_existing_keys
method above, so you may have to store an array of valid keys somewhere.Hopefully that's a sufficient starting point.
您可以引入这样的自定义验证:
不确定这是否有效,但您有回调和验证,并且可以使用两者来确保没有任何更改。
http://mongomapper.com/documentation/plugins/callbacks.html
http://mongomapper.com/documentation/plugins/validations.html
you can introduce a custom validation like this:
not sure if this will work but you have callbacks and validation and you can use both to make sure nothing is changed.
http://mongomapper.com/documentation/plugins/callbacks.html
http://mongomapper.com/documentation/plugins/validations.html