Rails ActiveModel-更新嵌套属性并添加新属性

时间:2020-06-11 16:29:38

标签: ruby-on-rails activerecord rails-activerecord

所以我很难用这个词来写标题,但是我是一个相当大的新手。我现在拥有的是Form批准的has_many


class Form < ApplicationRecord
 has_many :form_results
 has_many :approvals

 accepts_nested_attributes_for :approvals
end

class Approval < ApplicationRecord
 belongs_to :form
 belongs_to :user
end

编辑:approvals时,我需要运行一些逻辑。批准是连续的,因此它们具有一个order_index和一个active键(类似于软删除)。创建FormResult时,将根据该表单的FormResultApprovals中的数据创建多个Approvals。更新表单时需要做的事情,我需要查看是否已更改现有order_index的批准。如果需要,我需要将现有的批准标记为active: false并为此Approval创建一个新的order_index

我想知道这样做的“路线”是什么?我有大量的逻辑可以检查所有这些内容并起作用,但是随着我发现越来越多的Rails助手,我不禁想到了一种更好的方法。

我现在的代码如下

# Grab all current approvals for form that is being edited
# Diff the current against the new ones in the attributes
# If any have of the current approvals have the same id as the "new" ones in the attributes but have a different user associated to them, set active to false on the current approval with that id, and insert a new approval associated to the new user.

如果这与众不同,我正在使用SimpleForm。

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

这就是我想出的。

class Approval < ApplicationRecord
  default_scope { where(active: true) }
  belongs_to :form_module
  belongs_to :user, optional: true
  belongs_to :group, optional: true

  before_update :handle_change_in_approver


  def create_copy_model
    new_approval = Approval.new(order_index: order_index, user_id: user_id, group_id: group_id, form_module_id: form_module_id)
    new_approval.save
    self.active = false
    self.user_id = user_id_was
    self.group_id = group_id_was
    save
  end

  def handle_change_in_approver
    # User ID changed
    if user_id_was != user_id
      create_copy_model
    elsif group_id_was != group_id
      create_copy_model
    end
    form.form_results.each(&:create_approvals_for_approval_change)
  end
end

基本上,每当记录更新时,我都会在更新之前运行回调,以检查group_id或user_id是否已更改。如果有,那么我将基于更新参数创建一个新的Approval,然后将当前的Approval返回到其原始状态,将其标记为active: false。我对结果如何感到非常兴奋。

相关问题