Mongoid: How to prevent undefined fields from being created by mass assignment?

 ̄綄美尐妖づ 提交于 2019-12-05 08:49:12

I'm always using attr_accessible in models. I rarely found myself including all fields as accessible. Usually there are always a few fields that shouldn't be accessible for mass assignment. If you often need to include every attribute and you're concerned about duplication:

attr_accessible *fields.keys

What I have done to solve this issue, is use a before save callback in my model:

set_callback(:save, :before) do |doc|
    (doc.attributes.keys - fields.keys).each { |f| doc.unset(f) }
end

This way, even if there are extra attributes they get removed before being saved.

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