Post
和Comment
,我想选择帖子,并在包含.joins()
且具有2个.where()
条件的注释上使用OR
和IN
。我想要产生这种东西的东西:
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_name
和Comment.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条件。我想要生成此内容的东西:...
Post
的has_many :comments
类上有一个注释关系,Rails足够聪明,知道当您将.where
与关系名一起使用时,您正在考虑每个注释的ID,然后您可以简单地编写ID。