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?
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
Documentation here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With