gpt4 book ai didi

ruby-on-rails - Rails 3 ActiveRecord where 子句,其中设置了 id 或 null

转载 作者:数据小太阳 更新时间:2023-10-29 08:53:53 26 4
gpt4 key购买 nike

我有一个 ActiveRecord,Annotation,有两列:user_id 和 post_id,可以为空。带有 null user_id 和 post_id 的注释是“全局”注释,适用于所有用户的所有帖子。

我想检索与特定用户的帖子关联的所有注释以及所有全局注释。在 MySQL 中,SQL 命令是

select * from annotations where (user_id = 123 and post_id = 456) or (user_id is null and post_id is null)

在 Rails 3 中,将其编码为 Annotation.where 子句的最佳方法是什么?

最佳答案

不幸的是,没有真正好的方法来使用 OR sql 语法。您最好的两个选择可能是使用绑定(bind)参数自己编写 where 子句:

annotations = Annotation.where("(user_id = ? and post_id = ?) OR (user_id is null and post_id is null)").all

或者您可以深入研究 Arel 并使用该语法来制作它(查看 asciicast's Arel post )。

警告调用中的所有内容都是伪代码,不知道如何处理“post_id is null”——您可能只需要传递“user_id is null and post_id is null"to or(),但我最好的猜测是:

annotations = Annotation.arel_table
annotations.where(annotations[:user_id].eq(123).
and(annotations[:post_id].eq(456)).
or(annotations[:user_id].eq(nil).and(annotations[:post_id].eq(nil))

关于ruby-on-rails - Rails 3 ActiveRecord where 子句,其中设置了 id 或 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6336952/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com