【问题标题】:Unable to UPDATE nested attributes even when providing record ID即使提供记录 ID,也无法更新嵌套属性
【发布时间】:2021-10-31 15:13:44
【问题描述】:

我正在尝试更新嵌套记录,但由于某种原因它不起作用并且我的更新操作被忽略。如果我在控制台中运行以下代码,它返回 true,但实际上没有为 field_values_attributes 更新任何内容,只有 steps_attributes 按预期工作 = 状态更新为 6。如果我删除“id”=>“35”,则创建新的 field_value很好,所以UPDATE有问题。传递 id 和 _destroy 参数时,DESTROY 操作也有效。

# 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.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

过去有其他人遇到过同样的问题吗? 谢谢,米罗

【问题讨论】:

  • 不应该是accepts_nested_attributes_for :field, allow_destroy: true。还要确保您的控制器被允许接受 field_attributes 的 id
  • 对不起,我没有正确复制。现在应该是原样了,我还添加了相关模型。
  • 可能是多态关联的原因?
  • 我更新了描述以反映新的发现和调查。

标签: ruby-on-rails accepts-nested-attributes


【解决方案1】:

解决方案:

attr_accessor :value(我的虚拟属性,未存储在使用nested_attributes 时Rails 未检测到更改的DB 中)替换为attribute :value

灵感来自Accepts Nested Attribute with a virtual attribute

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-25
    相关资源
    最近更新 更多