可能在这里做了一些愚蠢的事情,但这是我的基本千篇一律类:
class League < ActiveRecord::Base
private
def league_params
params.require(:full_name).permit!
end
end
在创建一个新的 League 实例时:
2.0.0-p0 :001 > l = League.new(full_name: 'foo', short_name: 'bar')
WARNING: Can't mass-assign protected attributes for League: full_name, short_name
我到底做错了什么?这是 Rails 4.0.0.beta1 构建 + Ruby 2.0
**更新**
我现在意识到强参数现在是在 Controller 中强制执行的,而不是在模型中。原来的问题仍然成立。如果它们在 Controller 级别被允许,如果我在 Rails 控制台中创建实例,我如何正确地将属性列入白名单?在这种情况下,我不需要也使用 attr_accessible
从而完全复制试图“修复”的强参数吗?
最佳答案
两件事。 league_params
定义在 Controller 中,而不是模型中。并且 params.require()
应该包含需要出现在参数中的模型名称,而不是属性。属性存在检查仍应在模型验证中。在使用 permit!
之前,请确保您确实想要允许访问 League 模型中的所有属性。所以,它应该是这样的:
class LeaguesController < ApplicationController
private
def league_params
params.require(:league).permit!
end
end
更新:
是的,如果您希望在直接访问模型时限制属性,则需要切换回使用模型中的 attr_accessible
。该功能已移至此 gem 中:https://github.com/rails/protected_attributes .
我认为假设如果您直接在控制台中使用模型,则不需要保护属性,因为您确切知道输入的内容。由于控制台对您的应用具有完全访问权限,因此控制整个数据库就像恶意分配属性一样容易。
关于ruby-on-rails - 在 Rails 控制台中创建实例时 Rails 4 强参数失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15960121/