2

我的协会看起来像这样:

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?

4

1 回答 1

0

一种解决方案是(不是直接的)..

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

您将获得所需的输出。

于 2017-05-10T12:56:26.363 回答