Rails 4 deleting nested attributes, works on create but not on edit/update

一笑奈何 提交于 2019-12-03 01:50:47

when you are doing

# Never trust parameters from the scary internet, only allow the white list through.
def patient_params
  params.require(:patient).permit!
end

it permits all of your attributes and it's not recommended. It's more of a hack rather than a solution.

If you look at your question

Rails 4 deleting nested attributes, works on create but not on edit/update

and if you look at your params permitted

# Never trust parameters from the scary internet, only allow the white list through.
def patient_params
  params.require(:patient).permit(:first_name, :last_name, medications_attributes: [:name, :_destroy])
end

This will work on creating patients but not on updating or editing them because when you create a new record it doesn't require you to permit id but when you want to update or edit a record you need its id to be permitted as well.

Fix:

Just pass the id attribute to permitted attributes and it will work for you

# Never trust parameters from the scary internet, only allow the white list through.
def patient_params
  params.require(:patient).permit(:id, :first_name, :last_name, medications_attributes: [:id,:name, :_destroy])
end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!