检索与 Rails 中关联资源的列之一匹配的对象

Retrive objects matching one of the column of associated resource in Rails

我有 BackgroundJob 作为

class BackgroundJob < ActiveRecord::Base

  belongs_to :resource, polymorphic: true

end

这里的资源是消息table

class Message < ActiveRecord::Base

  has_one :background_job, as: :resource

end

列消息:电子邮件、文本。 邮件的电子邮件列为

我想检索其资源电子邮件列等于 'demo@example.com' 电子邮件的所有 BackgroundJob 对象。

我们怎样才能达到上面的效果 background_jobs table ?

消息作为 BackgroundJob 对象的资源。

我正在使用 mysql2 数据库。

您需要执行 JOIN,如下所示:

BackgroundJob.joins('INNER JOIN messages ON messages.id = background_jobs.resource_id AND background_jobs.resource_type = "Message"').where(messages: { email: 'demo@example.com' })

您不能使用 ActiveRecord 内置机制并简单地编写 joins(:resource),因为它是一个多态关联,甚至没有像 resources 这样的 table。这就是为什么你必须自己编写 JOIN 子句。