简体   繁体   English

按属性或JOIN表中的存在性查询行

[英]Querying rows by attribute or by existance in JOIN table

I have the entities A and B (with their respective tables). 我有实体A和B(以及它们各自的表)。 Those entities have a N:M relationship, so there is an AB table. 这些实体具有N:M关系,因此有一个AB表。

The A entity has a disabled boolean field. A实体具有disabled布尔字段。

I want to get all entities from A that ( are not disabled OR are in the AB table and belong to B entity with id 1 ) using ActiveRecord. 我想使用ActiveRecord从A中获取所有实体( are not disabledare in the AB table and belong to B entity with id 1 )。

Example: 例:

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 entities for Bob: foo , bar ans zoo . Bob A实体: foobar ans zoo

A.includes(:bs).where('as.disabled = false OR bs.id = 1')

A.where(:disabled => false ) will find all the entries from A that are not disabled and B.find_by_id(1).as will find all the entries from A that belong to B entity with id 1. A.where(:disabled => false ) | B.find_by_id(1).as A.where(:disabled => false )会发现从A不在禁用所有条目B.find_by_id(1).as会发现所有从A属于乙实体ID为1的条目A.where(:disabled => false ) | B.find_by_id(1).as A.where(:disabled => false ) | B.find_by_id(1).as taking OR of the 2 arrays gives the required entries. A.where(:disabled => false ) | B.find_by_id(1).as采用2个数组的OR来提供所需的条目。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM