【问题标题】:How to search in Active Record with the condition A + B如何使用条件 A + B 在 Active Record 中搜索
【发布时间】:2021-10-06 11:24:06
【问题描述】:

我想为与一个人关联的维护和能力指定每个条件并检索它们中的每一个。

通常,查询将检索包含两个条件的记录,Person.maintenances 和 Person.abilities。

A = Person.maintenances.where(~~~~)
B = Person.abilities.where(~~~)

我想以 Person 的身份在单个查询中获取以上所有内容。 (我想要的 = A + B 在单个查询中)

另外,我不希望有N+1的问题,但是我想知道如何防止发出查询,因为Person.maintenances和Person.abilities的条件是分开的。

class Person << ApplicationRecord
  has_many :maintenances
  has_many :abilities
end

class Maintenance << ApplicationRecord
  belongs_to :person
end

class Ability << ApplicationRecord
  belongs_to :person
end

※我用的是MySQL

谢谢。

【问题讨论】:

  • 您的查询在哪里?请与示例数据共享表结构并查询您遇到的问题。
  • 代码中的小错误:Person.maintenances 应该是 person.maintenances。对象Person 没有类方法maintenances。您应该在两个查询中执行此操作。一个将返回一个Maintenance 对象数组,另一个返回一个Ability 对象数组。如果您将它们连接起来(这可能在两个查询之后),则使用结果的代码将必须区分不同的对象(维护和能力),除非它们有一些通用方法。

标签: mysql sql ruby-on-rails activerecord


【解决方案1】:

一个简单的连接就可以解决问题:

Person.joins(:maintenance).where(maintenances: {status: 0, example: "yes"}).joins(:ability).where(abilities: {........})

或类似的东西,应该会产生相同的结果

Person.where(maintenances: Maintenance.where(person: self, ......), abilities: Ability.where(person: self, ......))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-07
    • 2017-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-26
    • 1970-01-01
    相关资源
    最近更新 更多