【问题标题】:Querying rows by attribute or by existance in JOIN table在 JOIN 表中按属性或存在查询行
【发布时间】:2016-10-18 07:48:18
【问题描述】:

我有实体 A 和 B(以及它们各自的表)。这些实体具有 N:M 关系,因此有一个 AB 表。

A 实体有一个disabled 布尔字段。

我想使用 ActiveRecord 从 A 获取所有实体(are not disabledare in the AB table and belong to B entity with id 1)。

例子:

A  
| id | name | disabled |
| a1 | foo  | false    |
| a2 | bar  | false    |
| a3 | zoo  | true     |
| a4 | hoo  | true     |

B
| id | name |
| 1  | Bob  |
| 2  | Jen  |

AB
|Aid | Bid |
| a3 | 1   |

A Bob 的实体:foobarzoo

【问题讨论】:

    标签: ruby-on-rails rails-activerecord ruby-on-rails-5


    【解决方案1】:
    A.includes(:bs).where('as.disabled = false OR bs.id = 1')
    

    【讨论】:

      【解决方案2】:

      A.where(:disabled => false ) 将查找 A 中未禁用的所有条目,B.find_by_id(1).as 将查找 A 中属于 ID 为 1 的 B 实体的所有条目。A.where(:disabled => false ) | B.find_by_id(1).as 对 2 个数组进行 OR 得到所需条目.

      requeried_entries = A.where(:disabled => false ) | B.find_by_id(1).as

      【讨论】:

      • 虽然这段代码 sn-p 可以解决问题,但它没有解释为什么或如何回答这个问题。请include an explanation for your code,因为这确实有助于提高您的帖子质量。请记住,您是在为将来的读者回答问题,而这些人可能不知道您提出代码建议的原因。
      • A.where(:disabled => false ) 将查找 A 中未禁用的所有条目,B.find_by_id(1).as 将查找 A 中属于 ID 为 1 的 B 实体的所有条目。A.where(:disabled => false ) | B.find_by_id(1).as 对 2 进行 OR数组给出所需的条目。
      • edit您的答案添加对您的代码的作用以及应该使用它的原因的描述。避免在 cmets 中添加它,因为它们更难阅读并且更容易删除。
      猜你喜欢
      • 2011-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-28
      • 1970-01-01
      相关资源
      最近更新 更多