【问题标题】:Scope join table to build new association范围连接表以建立新的关联
【发布时间】:2019-09-19 07:49:47
【问题描述】:

我想确定一个连接表的范围并创建一个新的关联。

在我的连接表 (PrestaMission) 中,我存储了两个值(:assigned 和 :proposed)。所以我想创建一个新的关联来在我的模型中创建两个 has_many。

我给你代码,它会最清楚。

模型任务:

class Mission < ApplicationRecord
  has_many :presta_missions, dependent: :destroy
end

连接表(PrestaMission)

class PrestaMission < ApplicationRecord
  belongs_to :client, polymorphic: true
  belongs_to :mission

  scope :assigned, -> { where(assigned: true) }
  scope :proposed, -> { where(proposed: true) }
end

还有模型Keyper(PrestaMission的客户端之一)

class Keyper < ApplicationRecord
  has_many :presta_missions, as: :client, dependent: :destroy
  has_many :missions, through: :presta_missions

  has_many :assigned_prestas, -> { where(assigned: true) }, :class_name => 'PrestaMission'
  has_many :assigned_missions, through: :assigned_prestas

  has_many :proposed_prestas, -> { where(proposed: true) }, :class_name => 'PrestaMission'
  has_many :proposed_missions, through: :proposed_prestas
end

但是这个链接关联的脚本目前不工作。有什么建议吗?

【问题讨论】:

    标签: ruby-on-rails polymorphic-associations


    【解决方案1】:

    我找到了一个优雅的解决方案来解决这个问题:

      has_many :presta_missions, as: :client, dependent: :destroy
      has_many :missions, :through => :presta_missions do
        def assigneds
          where("presta_missions.assigned = ?", true)
        end
        def proposeds
          where("presta_missions.proposed = ?", true)
        end
      end
    

    要调用此关联,您现在可以使用以下命令

    @keyper.missions.proposeds
    OR
    @keyper.missions.assigneds
    

    好好利用,玩得开心!!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-17
      相关资源
      最近更新 更多