Rails Devise attr_accessible 问题
我正在尝试向我的 Rails 3 应用程序添加设备授权。 一切都很顺利,除了我还尝试按照这个教程来动态设置 attr_accessible role_ids 仅适用于管理员用户(我不希望普通用户更改其角色,但管理员应该能够这样做)...问题是,railscast 教程方法假设我有权更改控制器行为,而实际上设计是在幕后处理所有这些。
请帮忙
Im trying to add devise authorization to my rails 3 app.
Its all going well except Im also trying to follow this tutorial to dynamically set attr_accessible for role_ids only for admin users (I dont want regular users changing their role, but an admin should be able to do so)... the problem is, the railscast tutorial approach assumes I have access to change the controller behavior when in fact devise is handling all that under the hood.
Please Help
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以对 Devise 控制器进行子类化,只需生成视图并将它们移动到正确的位置即可。查看 Devise 自述文件中的“配置视图”和“配置控制器”。
我最终将 role_ids 添加到 attr_accessible,然后对 RegistrationsController 进行子类化并添加 before_filter 以删除非管理员的该参数。
只需确保将注册视图添加到
/app/views/users/registrations/
即可。You can subclass the Devise controllers, you just have to generate the views and move them to the correct place. Check out "Configuring views" and "Configuring controllers" in the Devise readme.
I ended up adding role_ids to attr_accessible, then subclassing the RegistrationsController and adding a before_filter to remove that param for non-admins.
Just make sure to add the registration views to
/app/views/users/registrations/
.我发现处理此问题的最佳方法来自 RailsCast 237。它比 Arrel 的答案更详细,但它不会强制您将角色(或其他字段)添加到 attr_accessible。
在初始化程序中添加以下方法:
然后在控制器中,您可以执行以下操作:
user.accessible = :role if can? :set_role, resources
不幸的是,这个调用必须在用户(或其他)对象实例化之后进行。这意味着您必须对控制器进行子类化,并在更新和创建中的资源实例化之后调用它。
这是针对 Rails 3.2 的。在早期版本中,我相信 Mass_assignment_authorizer 方法不带参数。没有值的 attr_accessible 设置故障安全应用程序范围拒绝批量分配。这也可以在 application.rb 文件中完成
The best way I found to handle this is from RailsCast 237. It is more verbose than Arrel's answer, but it does not force you to add role (or other fields) to attr_accessible.
Add the following method in an initializer:
Then in your controller, you can do:
user.accessible = :role if can? :set_role, resource
This call, unfortunately, has to be made after the user (or whatever) object has been instantiated. That means that you would have to subclass the controller, and call this after the resource instantiation in update and create.
This is for Rails 3.2. In earlier versions I believe the method mass_assignment_authorizer does not take a parameter. The attr_accessible with no values sets a fail-safe application wide denial for mass assignment. This can also be done in the application.rb file with