Ruby-on-rails Rails 4 强参数:permit 的所有属性?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14033908/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rails 4 Strong parameters : permit all attributes?
提问by Nicolas Blanco
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?
你有没有想到更好的方法?
采纳答案by vvo
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!
大功告成,现在您可以随心所欲地玩了!
回答by Damon Aw
You can call the bang version of permit.
你可以调用 bang 版的permit。
params.require(:user).permit!
Strong Params README on 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
回答by Anthony Sallows
Skull0inc's answer works, but you might want to remove created_atand updated_at. The intention of strong params is to list only the attributes you want updatable by the controller.
Something like...
Skull0inc 的答案有效,但您可能想要删除created_at和updated_at。strong params 的目的是仅列出您希望控制器更新的属性。就像是...
def user_params
params.require(:user).permit(User.column_names - ["created_at", "updated_at"])
end
回答by Skull0inc
Would this work?
这行得通吗?
def user_params
params.require(:user).permit(User.column_names)
end

