ruby-on-railsaccepts-nested-attributes

Unable to UPDATE nested attributes even when providing record ID


I am trying to update nested records, but for some reason it does not work and my update action is ignored. If I run the following code in console, it returns true, but nothing is actually updated for field_values_attributes, only steps_attributes work as expected = status is updated to 6. If I remove "id"=>"35", the new field_value is created just fine, so there is something wrong with UPDATE. Also the DESTROY action is working when passing id and _destroy params.

# CREATE - WORKING
myrecord.update("status"=>6, "field_values_attributes"=>[{"value"=>"new_value"}])

# UPDATE - NOT WORKING
myrecord.update("status"=>6, "field_values_attributes"=>[{"id"=>"35", "value"=>"new_value"}])

# DESTROY- WORKING
myrecord.update("status"=>6, "field_values_attributes"=>[{"id"=>"35", "_destroy"=>"1"}])

FieldValue model

# FieldValue.rb
class FieldValue < ApplicationRecord
  attr_accessor :value

  belongs_to :field, class_name: 'FieldInput', foreign_key: 'field_component_id'
  before_validation :set_value

  private
  def set_value
    # when run in debug mode, the following code is not executed / ignored for UPDATE action, working fine for CREATE action
    case field.field_type.key
    when 'text'
      self.text_value = value
    when 'number'
      self.number_value = value
    when 'date'
    else
      self.string_value = value
    end
  end

ExecutionStep.rb

class ExecutionStep < ApplicationRecord
  has_many :field_values, class_name: 'FieldValue', as: :valueable, dependent: :destroy

  enum status: { not_started: 0, in_progress: 1, paused: 3, retry: 4, completed: 5, failed: 6, canceled: 7 }

  accepts_nested_attributes_for :field_values, allow_destroy: true
end

Anyone else run into same issues in the past? Thanks, Miro


Solution

  • SOLUTION:

    replace attr_accessor :value (my virtual attribute, not stored in DB for which the change is not detected by Rails when using nested_attributes) with attribute :value

    Inspired by Accepts Nested Attribute with a virtual attribute