Rails 3 ActiveRecord where子句设置的子句或null

时间:2011-06-13 22:03:52

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

我有一个ActiveRecord,Annotation,有两列:user_id和post_id,可以为null。具有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子句的最佳方法是什么?

1 个答案:

答案 0 :(得分:3)

不幸的是,使用OR sql语法并没有什么好方法。您最好的两个选项可能是使用绑定参数自己编写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)。

警告or调用中的所有内容都是psuedocode,不知道怎么做'post_id为null' - 你可能只需传递“user_id为null且post_id为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))