jeudi 7 mai 2020

Rails - Object in has_many relation is not getting updating

I am having a table called Groups, where Groups and Sub-Groups are saved. A group has_many sub-group. Below is the code

groupone.rb (one of the main group)

class GroupOne < BaseGroup
  belongs_to :parent, class_name: 'GroupOne'
  has_many :sub_group_one, autosave: true, dependent: :destroy, inverse_of: :groupone
end

reports_controller.rb

class ReportsController < ActionController::Base

  def process_report
    current_record = load_from_xml(xml_path)
    current_group = current_record.last
    base_report_group = find_or_create_base_group(current_group)
    process_sub_group(current_group, base_report_group)
    base_report_group.save

  end

  def process_sub_group(current_group, base_report_group)
    if current_group.sub_group_one.present?
      current_group.sub_group_one.each do |sub_group|
        sgroup = base_report_group.sub_group_one.find_or_initialize_by(group_type_id: sub_group.group_type, serial_num: sub_group.serial_num)
        sgroup.attributes = {name: "Rob", age: 12}
      end
  end

end

The above code is creating new GroupOne and many sub_group_one records with out any issues but when i try to update the existing sub_group_one values, they are not getting updated. For example {name: "Rob", age: 12} is not getting updated to any of the sub-group record. I noticed that the new attributes are assigned to sgroup during the current sub_group iteration and once all the sub_group iteration are completed, when i do binding.pry for base_report_group.sub_group_one it shows the old record and this is the issue.

Can any one please help me to fix this. Thank you

Aucun commentaire:

Enregistrer un commentaire