Rails 4 strong parameters without required parameters

£可爱£侵袭症+ 提交于 2019-12-03 15:14:00

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/25914514/rails-4-strong-parameters-without-required-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!