我有一个 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”到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/