从关注创建与另一个模型的belongs_to关联

问题描述

我有一个多态模型和几个正常模型之一。

class Task
  belongs_to :taskable,polymorphic: true
end

class Building
  include Taskable
end

我有以下担忧/担忧。

module Taskable
  extends ActiveSupport::Concern

  included do
    has_many :tasks,as: :taskable
  end

  class_methods do
    def tasks
      Task.where(taskable: all)
    end
  end
end

在我们的应用中,我们需要能够在特定模型(例如建筑)上加入Task。我们可以通过在Task模型中添加以下belongs_to来实现这一目标。

belongs_to :building,-> { where(tasks: { taskable_type: Building.name }) },foreign_key: taskable_id,foreign_type: Building.name

但是,每当我们要使另一个模型成为Taskable模型时,我们都需要手动添加这个Emirates_to。我们希望关注点自动在Task上创建一个Emirates_to关联。我们使用元编程来为扩展类创建关联,但是该关联仅在加载类时创建。我希望在启动控制台时(与服务器相同)创建belongs_to。

# In Taskable concern.
# Is only called when we load a performable in the console.
Task.belongs_to class.name.to_sym,-> { where(tasks: { taskable_type: class.name }) },foreign_type: class.name

有没有办法使这项工作成功?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)