我的关联如下所示:
class Abc < ApplicationRecord
has_many :def
accepts_nested_attributes_for :def, allow_destroy: true
end
class AbcController < ApplicationController
def update
abc = Abc.find(params[:id])
if abc.update(abc_params)
# TODO Here update is sucessful but how to get all newly added def in database with their id?
end
end
private
def abc_params
params.require(:abc).permit(def_attributes: [:name, :title,:wordcount, :id])
end
end
我们知道accepts_nested属性在数据库中创建了一个新的嵌套对象,那么如何在AbcController更新函数中获取所有新添加(尚未存在(的def对象及其数据库ID?
一种解决方案是(不是直接的(。
def update
abc = Abc.find(params[:id])
number_of_defs = abc.defs.length
if abc.update(abc_params)
number_newly_added_defs = abc.defs.length - number_of_defs
newly_added_defs = abc.defs.last(number_newly_added_defs)
end
end
您将获得所需的输出。