使用ransack使用不同的WHERE子句多次加入同一关联

我有属于tag_set的项目和标签。这些项目被标记在 注释。一个注释具有has_many标签和belongs_to项, 属于用户。

我想动态地使用Ransack(或者如果不可能的话使用常规导轨) 生成表单和查询,让用户查找与标签匹配的项目 来自不同的tag_sets,例如查找(红色或蓝色)AND(XS)的项目 或S),在这种情况下为“鞋子和衬衫”。每个TagSet应该有自己的多个 选择表单元素。 TagSet是动态创建的,查询应涵盖 所有标记集。

我有下表,请参见sqlfiddle:http://sqlfiddle.com/#!9/d1a730/8

项目表

|id|name  |
|--|------|
| 1|Shoe  |
| 2|Socks |
| 3|Pants |
| 4|Shirt |
| 5|Hat   |
| 6|Jacket|

tag_sets表

|id|name |
|--|-----|
| 1|Color|
| 2|Size |

标签表

|id|tag_set_id|name |
|--|----------|-----|
| 1|         1|Red  |
| 2|         1|Blue |
| 3|         1|Pink |
| 4|         1|Green|
| 5|         1|Black|
| 6|         1|White|
| 7|         2|XS   |
| 8|         2|S    |
| 9|         2|M    |
|10|         2|L    |
|11|         2|XL   |

用户表

|id|Name |
|--|-----|
| 1|Mark |
| 2|Jane |
| 3|Diana|

注释表

|id|user_id|item_id|
|--|-------|-------|
| 1|      1|      1|
| 2|      1|      1|
| 3|      2|      2|
| 4|      2|      3|
| 5|      3|      4|
| 6|      3|      4|
| 7|      3|      4|

annotations_tags联接表

|annotation_id|tag_id|
|-------------|------|
|            1|     1|
|            1|     2|
|            2|     7|
|            2|     8|
|            3|     2|
|            4|     7|
|            5|     1|
|            5|     3|
|            6|     4|
|            6|     5|
|            7|     7|
|            7|     9|

我已经创建了以下红宝石代码:

Item.joins('LEFT OUTER JOIN annotations a1 ON a1.item_id = items.id').
     joins('LEFT OUTER JOIN annotations_tags at1 ON at1.annotation_id = a1.id').
     joins('LEFT OUTER JOIN tags t1 ON t1.id = at1.tag_id').
     joins('LEFT OUTER JOIN annotations a2 ON a2.item_id = items.id').
     joins('LEFT OUTER JOIN annotations_tags at2 ON at2.annotation_id = a2.id').
     joins('LEFT OUTER JOIN tags t2 ON t2.id = at2.tag_id').
     where('t1.id' => [1,2]).
     where('t2.id' => [7,8])

哪个生成此sql:

SELECT DISTINCT items.* 
FROM items 

LEFT OUTER JOIN annotations a1 ON a1.item_id = items.id 
LEFT OUTER JOIN annotations_tags at1 ON at1.annotation_id = a1.id 
LEFT OUTER JOIN tags t1 ON t1.id = at1.tag_id 

LEFT OUTER JOIN annotations a2 ON a2.item_id = items.id 
LEFT OUTER JOIN annotations_tags at2 ON at2.annotation_id = a2.id 
LEFT OUTER JOIN tags t2 ON t2.id = at2.tag_id 

WHERE 
  t1.id IN (1,2)
AND
  t2.id IN (7,8)

是否可以使用ransack构建此查询?

jl316 回答:使用ransack使用不同的WHERE子句多次加入同一关联

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/3111344.html

大家都在问