使用 Squeel 自定义查询两个属性与有序对的相等性
我在编写查询时遇到困难,无论是否使用 SQL,但我希望能够使用 gem Squeel 在 ruby 中编写它。基本上,我有一个类:
class Article < ActiveRecord::Base
belongs_to :genre
belongs_to :publisher
...
end
我想要一个范围,它接受格式为 (genre_id,publisher_id)
的有序对数组,并输出一个 ActiveRecord::Relation
,其中包含所有具有流派的记录,出版商对等于传入的对。
基本上,我想要 Article.where{ Genre_id.eq_any [1, 5, 76] }
,除了而不是单个属性,我想它在一对属性上:
Article.where{ genre_id_publisher_id.eq_any [(1,2), (1,4), (2, 4)] }
我能想到的唯一方法是使用 select 调用创建一个作用域,该调用添加一个列,该列将是两个 id 与某个分隔符的串联,然后基于此进行搜索:
Article.select(*,
"#{genre_id}-#{publisher_id}" as genre_publisher_pair).where(
genre_publisher_pair.eq_any ["1-2", "1-4", "2-4"])
但是,似乎开销太大了。我还已经在 [genre_id,publisher_id] 上有一个复合索引,恐怕这不会使用该索引,这对我来说是一个要求。
有没有更简单的方法来编写这些复合作用域?谢谢!
I'm having difficulty writing a query, whether in SQL or not, but I'd like to be able to write it in ruby using the gem Squeel. Basically, I have a class:
class Article < ActiveRecord::Base
belongs_to :genre
belongs_to :publisher
...
end
I want a scope that takes in an array of ordered pairs of the format (genre_id, publisher_id)
and outputs an ActiveRecord::Relation
that contains all of the records with genre, publisher pairs equal to the pairs passed in.
Basically, I want Article.where{ genre_id.eq_any [1, 5, 76] }
, except instead of a single attribute, I want it on a pair of attributes:
Article.where{ genre_id_publisher_id.eq_any [(1,2), (1,4), (2, 4)] }
The only way I can think of doing it is making a scope with a select call that adds a column which would be the concatenation of the two ids with some delimiter, then searching based on that:
Article.select(*,
"#{genre_id}-#{publisher_id}" as genre_publisher_pair).where(
genre_publisher_pair.eq_any ["1-2", "1-4", "2-4"])
However, that seems like too much overhead. I also already have a compound index on [genre_id, publisher_id] and I'm afraid this won't use that index, which is going to be a requirement for me.
Is there an easier way to write these compound scopes? Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论