[英]Rails 4 Strong parameters : permit all attributes?
I'm building a web app with Rails 4 strong parameters.我正在构建一个带有 Rails 4 强参数的网络应用程序。
When building the admin back office controllers, I wonder what is the best way to permit all the model attributes?在构建后台管理控制器时,我想知道允许所有模型属性的最佳方法是什么?
For now, I wrote this:现在,我写了这个:
def user_params
params.require(:user).permit(User.fields.keys)
end
Do you think of a better way?你有没有想到更好的方法?
You can call the bang version of permit.你可以调用 bang 版的permit。
params.require(:user).permit!
Strong Params README on Github Github 上的强参数自述文件
Source code for reference:参考源代码:
def permit!
each_pair do |key, value|
convert_hashes_to_parameters(key, value)
self[key].permit! if self[key].respond_to? :permit!
end
@permitted = true
self
end
Just in case someone need it for Rails 6, without even a model linked to your controller, you can use:万一有人需要它用于 Rails 6,甚至没有链接到您的控制器的模型,您可以使用:
before_action :accept_all_params
private
def accept_all_params
params.permit!
end
And done, now you can play with 🔥 as much as you want!大功告成,现在您可以随心所欲地玩 🔥 了!
Skull0inc's answer works, but you might want to remove created_at
and updated_at
. Skull0inc 的答案有效,但您可能想要删除created_at
和updated_at
。 The intention of strong params is to list only the attributes you want updatable by the controller. strong params 的目的是仅列出您希望控制器更新的属性。 Something like...就像是...
def user_params
params.require(:user).permit(User.column_names - ["created_at", "updated_at"])
end
Would this work?这行得通吗?
def user_params
params.require(:user).permit(User.column_names)
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.