我的联想是这样的:
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
您将获得所需的输出。
关于ruby-on-rails - 我们如何在使用 rails 中的 accepts_nested_attributes_for 关联更新后只获取新添加的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43887278/