创建记录时,请从关联的记录中复制属性

时间:2019-03-28 04:11:45

标签: ruby-on-rails

在我的Rails待办应用中,我有一个Tasks模型。任务可以彼此blocked_by。每个任务都有一个用户。当我执行taskA.blocked_by.create(name: "Task B")时,我希望任务B获得与任务A相同的用户。

问题是,我不知道如何引用创建当前记录的记录。我需要学习如何获取taskA.user,以便可以将其自动分配给taskB。我宁愿不必在每次创建blocked_by任务时手动执行该操作。

我尝试用self.user方法设置before_validation

before_validation :inherit_user, on: :create

private
    def inherit_user
        if self.user == nil 
            p "Task #{self.name} missing user"
            if self.blocked_by.count > 0
                self.user = self.blocked_by.first.user
                p "Inheriting user from first blocked_by task #{self.blocked_by.first.name}"
            end
        end
    end

这不起作用,因为self.blocked_by为空,因为尚未保存记录。

Rails' documentation on association class methods使我相信我应该能够执行以下操作:

has_many :blocked_by do |owner|
    def create(attributes)
        p owner # access properties from association owner here
        attributes.push(user: owner.user)
        super
    end
end

当我尝试此操作时,我得到:

NoMethodError (undefined method `owner' for #<ActiveRecord::Associations::CollectionProxy []>)

编辑:这是我的模型文件:

class Task < ApplicationRecord
    validates :name, :presence => true

    belongs_to :user

    has_many :children, class_name: "Task", foreign_key: "parent_id"
    belongs_to :parent, class_name: "Task", optional: true
    has_ancestry

    # thanks to https://medium.com/@jbmilgrom/active-record-many-to-many-self-join-table-e0992c27c1e
    has_many :blocked_blocks, foreign_key: :blocker_id, class_name: "BlockingTask"
    has_many :blocked_by, through: :blocked_blocks, source: :blocking, dependent: :destroy

    has_many :blocker_blocks, foreign_key: :blocked_id, class_name: "BlockingTask"
    has_many :blocking, through: :blocker_blocks, source: :blocker, dependent: :destroy

    has_many_attached :attachments

    before_validation :inherit_user, on: :create

    def completed_descendants
        self.descendants.where(completed: true)
    end

    def attachment_count
        self.attachments.count
    end

    private
        def inherit_user
            if self.user == nil and self.parent
                self.user = self.parent.user
            end
        end

end

我可以inherit_user来自上级任务,例如:taskA.children.create(name: "Task B")。我想为blocked_by关系做同样的事情。

1 个答案:

答案 0 :(得分:0)

要引用应该创建的当前记录,请尝试运行before_create回调。

 before_create :inherit_user

self.blocked_by现在必须有一个值。

相关问题