本文介绍了当遇到在早期版本的 Rails 中使用 attr_accessible 的情况时,Rails 4 中的禁止属性错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近升级到 Rails 4,使用类似于下面的代码更新属性不起作用,我收到一个 ActiveModel::ForbiddenAttributes 错误:

With the recent upgrade to Rails 4, updating attributes using code resembling the below does not work, I get a ActiveModel::ForbiddenAttributes error:

@user.update_attributes(params[:user], :as => :admin)

其中用户在模型中有以下 attr_accessible 行:

Where User has the following attr_accessible line in the model:

attr_accessible :role_ids, :as =>admin
# or any attribute other than :role_ids contained within :user

你如何在 Rails 4 中完成同样的任务?

How do you accomplish the same task in Rails 4?

推荐答案

Rails 4 现在具有来自 strong_parameters 的功能 gem 默认内置.

Rails 4 now has features from the strong_parameters gem built in by default.

人们不再需要拨打电话 :as =>:admin,你也不需要 attr_accessible :user_attribute, :as =>admin 在您的模型中.这样做的原因是,默认情况下,rails 应用程序现在对模型上的每个属性都有安全性".您必须允许您要访问/修改的属性.

One no longer has to make calls :as => :admin, nor do you need the attr_accessible :user_attribute, :as => admin in your model. The reason for this is that, by default, rails apps now have 'security' for every attribute on models. You have to permit the attribute you want to access / modify.

您现在需要做的就是在 update_attributes 期间调用 permit:

All you need to do now is call permit during update_attributes:

@user.update_attributes(params[:user], permit[:user_attribute])

或者,更准确地说:

@user.update_attributes(params[:user].permit(:role_ids))

然而,这一行允许任何用户修改 permitted 角色.您必须记住,仅允许管理员或任何其他所需角色通过其他过滤器(例如以下内容)访问此操作:

This single line, however, allows any user to modify the permitted role. You have to remember to only allow access to this action by an administrator or any other desired role through another filter such as the following:

authorize! :update, @user, :message => 'Not authorized as an administrator.'

...如果您使用 Devise 和 CanCan 进行身份验证和授权,这将起作用.

. . . which would work if you're using Devise and CanCan for authentication and authorization.

这篇关于当遇到在早期版本的 Rails 中使用 attr_accessible 的情况时,Rails 4 中的禁止属性错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-19 05:41