替换 params 哈希中的敏感元素以避免 Rails 中的大量分配
我希望给自己一个更系统的解决方案,避免大量分配。
典型的情况是从参数中删除 id 或 user_id (通过表单自动提交)并在内部将其替换为 current_user.id (在 MyController#create 中)。
我能想到的一个解决方案是从 params 哈希创建对象,然后 update_attributes (父对象和子对象的)以用内部值替换敏感属性:
@user = User.create(:params[:user])
@user.update_attributes(:id => current_user.id)
@user.profile.update_attributes(:user_id => current_user.id)
@user.preference.update_attributes(:user_id => current_user.id)
是否有更短/更干燥的方式来表达这一点?
如果首选项、配置文件等是用户的子对象(通过构建方法创建),我如何编写一个方法来查找用户的外键并自动将它们替换为我传递给父级的值?
谢谢。
I would like to have a more systematic solution for myself to avoid mass assignment.
A typical situation is to remove id or user_id from params (submitted automatically via form) and replace it with current_user.id internally (in MyController#create).
A solution I can think of is to create object from params hash, then update_attributes (of parent and child objects) to replace sensitive attributes with internal values:
@user = User.create(:params[:user])
@user.update_attributes(:id => current_user.id)
@user.profile.update_attributes(:user_id => current_user.id)
@user.preference.update_attributes(:user_id => current_user.id)
Is there a shorter/more DRY way to say this?
If preference, profile etc. are child objects of user (created via build method), how can I write a method to look for their foreign keys for user and automatically replace them with the value I passed to parent?
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这就是
attr_protected
和attr_accessible
(文档) 用于。attr_protected
将为您提供黑名单保护,而attr_accessible
将使用白名单进行保护。在批量分配生效后立即调用
update_attributes
时,您最好使用内置的方法来保护批量分配,因为每次对某个对象进行批量分配时都不需要重复代码。模型。This is what
attr_protected
andattr_accessible
(documentation) are for.attr_protected
will give you blacklist protection, whileattr_accessible
will protect using a whitelist.While calling
update_attributes
right after a mass assignment would work, you're better off using the built in ways of protecting mass assignments as it won't require duplication of code every time you do a mass assignment on a model.我在早期的项目中使用以下方法完成了此操作:
这对您有用吗?
另一种方法是查看 docs 并搜索
:as
用于基于角色的属性。I've done this in an earlier project by using:
Would this work for you?
An alternative is to check out the docs and search for the
:as
for role based attributes.