Is there a way to set attr_accessible by default in a rails project with Mongoid?
-
25-05-2021 - |
题
The recommended solution is this:
config.active_record.whitelist_attributes = true
But this only works if you are using active record. On a mongoid rails project is there a similar approach? It uses active model but not active record.
解决方案
I have asked the same question
https://groups.google.com/forum/?fromgroups#!topic/mongoid/xuBbuyhiFEU
It is currently not supported but you can do a (straight forward) monkey patch (as Benedikt suggested)
https://gist.github.com/1977438
It is very similar to AR (you could check in AR code, I copy it here for simplicity)
ActiveSupport.on_load(:active_record) do
if app.config.active_record.delete(:whitelist_attributes)
attr_accessible(nil)
end
app.config.active_record.each do |k,v|
send "#{k}=", v
end
end
其他提示
I've never used Mongoid, so this is pretty speculative, but from the looks of it, AR uses a Railtie initializer to set attr_accessible(nil) when that config is true.
It doesn't look like there's currently way to do that in a config, but you could probably hook it somehow with your own initializer. In Mongoid::Fields, if the config for protect_sensitive_fields is true (the default), it calls attr_protected for id, _id, and _type. That also sets the active_authorizer to a blacklist. You could probably patch that up and give a better config for white list that calls attr_accessible(nil) instead.
So yeah, wouldn't be a bad idea to just make a patch then submit a pull request. The last thing the ruby community needs is another high profile mass assignment fiasco.
This will do the trick for now:
http://groups.google.com/group/mongoid/browse_thread/thread/de5a93a350b49c02?pli=1