按属性或 JOINT table 中的存在查询行
Querying rows by attribute or by existance in JOIN table
我有实体 A 和 B(及其各自的 table)。这些实体有 N:M 关系,所以有一个 AB table.
A 实体有一个 disabled
布尔字段。
我想使用 ActiveRecord 从 A 中获取所有实体(are not disabled
或 are 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 |
Bob 的 A
个实体:foo
、bar
和 zoo
。
A.includes(:bs).where('as.disabled = false OR bs.id = 1')
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
采用 OR 2 个数组中的一个给出了所需的条目。
requeried_entries = A.where(:disabled => false ) | B.find_by_id(1).as
我有实体 A 和 B(及其各自的 table)。这些实体有 N:M 关系,所以有一个 AB table.
A 实体有一个 disabled
布尔字段。
我想使用 ActiveRecord 从 A 中获取所有实体(are not disabled
或 are 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 |
Bob 的 A
个实体:foo
、bar
和 zoo
。
A.includes(:bs).where('as.disabled = false OR bs.id = 1')
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
采用 OR 2 个数组中的一个给出了所需的条目。
requeried_entries = A.where(:disabled => false ) | B.find_by_id(1).as