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:
我正在使用Rails 4,我不知道在没有必要参数的情况下使用强参数的最佳方式是什么。我就是这么做的:
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?
有什么惯例或者正确的方法吗?
1 个解决方案
#1
37
You can use fetch
instead of require
.
您可以使用fetch而不是require。
def device_params
params.fetch(:device, {}).permit(:notification_token)
end
Above will return empty hash when device is not present in params
当设备不在params中时,上面将返回空散列
Documentation here.
这里的文档。
#1
37
You can use fetch
instead of require
.
您可以使用fetch而不是require。
def device_params
params.fetch(:device, {}).permit(:notification_token)
end
Above will return empty hash when device is not present in params
当设备不在params中时,上面将返回空散列
Documentation here.
这里的文档。