本文介绍了Rails 4 强参数无必选参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用 Rails 4,但我不知道在没有必需参数的情况下使用强参数的最佳方法是什么.所以,这就是我所做的:
I'm using Rails 4 and I don't know what is the best way to use strong parameters without required parameters. So, that's what I did:
def create
device = Device.new(device_params)
.................
end
private
def device_params
if params[:device]
params.require(:device).permit(:notification_token)
else
{}
end
end
我的设备模型没有验证任何东西的存在.我知道我也可以做类似的事情:
My device model does not validate presence of anything.I know I could do something like that too:
device = Device.new
device.notification_token = params[:device][:notification_token] if params[:device] && params[:device][:notification_token]
是否有任何约定或正确的方法来做到这一点?
Is there any conventions or the right way to do that?
推荐答案
您可以使用 fetch
而不是 require
.
You can use fetch
instead of require
.
def device_params
params.fetch(:device, {}).permit(:notification_token)
end
当参数中不存在设备时,上面将返回空哈希
Above will return empty hash when device is not present in params
文档此处.
这篇关于Rails 4 强参数无必选参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!