【问题标题】:Retrive objects matching one of the column of associated resource in Rails检索与 Rails 中关联资源列之一匹配的对象
【发布时间】:2019-03-27 15:46:40
【问题描述】:

我有 BackgroundJob

class BackgroundJob < ActiveRecord::Base

  belongs_to :resource, polymorphic: true

end

这里的资源是消息表

class Message < ActiveRecord::Base

  has_one :background_job, as: :resource

end

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

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

我们如何实现上面的 background_jobs 表?

消息作为 BackgroundJob 对象的资源。

我正在使用 mysql2 数据库。

【问题讨论】:

    标签: ruby-on-rails activerecord mysql2


    【解决方案1】:

    你需要执行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 这样的偶数表。这就是为什么你必须自己编写JOIN 子句。

    【讨论】:

    • 谢谢,理解概念。用于创建范围
    猜你喜欢
    • 1970-01-01
    • 2014-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多