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

标签 ruby-on-rails ruby ruby-on-rails-3 activerecord

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

相关文章:

ruby-on-rails - 使用 postgres 和 redis 对 Rails 项目进行 Dockerize

ruby-on-rails - 在nodejs算法中创建签名 rsa-sha1 private_key.pem

ruby-on-rails - 从db到css文件?

ruby-on-rails - 如何绕过 default_url_options?

ruby - 如何匹配 URL 但从匹配中排除终止符?

ruby-on-rails - 使用集合向 Formtastic 单选按钮添加背景图像或图像标签

ruby-on-rails - 如何访问设计 token 授权注册 Controller ?

ruby-on-rails - 使用 shoulda-matchers 检查枚举值时出错

ruby - 覆盖 is_a 的正确方法是什么?和种类?

ruby - 用散列中的值替换键