2

My association looks like this :

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

We know accepts_nested attributes creates a new nested object in the database so how can I get all the newly added(not already existing) def object with their database id in AbcController update function ?

1 Answers1

0

One solution is (not a direct one)..

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

you will get the desired output.

Naveen Krishnan
  • 356
  • 2
  • 6