ActiveRecord .joins()并在具有“ OR”连接的2个“ IN”条件的连接模型上使用.where()。

问题描述 投票:0回答:1
问题

我有一个PostComment,我想选择帖子,并在包含.joins()且具有2个.where()条件的注释上使用ORIN

我想要产生这种东西的东西:

SELECT * FROM posts INNER JOIN comments ON comments.post_id = posts.id WHERE comments.id IN (1,2,3) OR comments.user_id IN (4,5,6)

我将使用.or()方法,但不能使用哈希。

Post.joins(Comment) .where({ comments: { id: [1, 2, 3] } }) .or({ comments: { user_id: [4, 5, 6] } }) # <-- raises exception

可能的解决方案

为了方便阅读,我对此进行了简化。实际上,我需要它来跨数据库适配器工作,因此我将使用Comment.connection.quote_table_nameComment.connection.quote_column_name正确引用表名和列名。

ids = [1,2,3] user_ids = [4,5,6] clause = "" clause += Comment.sanitize_sql_for_conditions(["comments.id IN (?)", ids]) if ids.any? clause += " OR " if ids.any? and user_ids.any? clause += Comment.sanitize_sql_for_conditions(["comments.user_id IN (?)", user_ids]) if user_ids.any? Post.joins(Comment).where(clause)

问题

这有效,但似乎应该有更好的方法...在那儿吗?

问题我有一个帖子和一个注释,我想选择帖子,并在注释上使用.joins()和.where(),该注释包含OR并具有2个IN条件。我想要生成此内容的东西:...

ruby-on-rails activerecord rails-activerecord
1个回答
0
投票
[我假设您在带有Posthas_many :comments类上有一个注释关系,Rails足够聪明,知道当您将.where与关系名一起使用时,您正在考虑每个注释的ID,然后您可以简单地编写ID。
© www.soinside.com 2019 - 2024. All rights reserved.