Rails 3 ActiveRecord where子句,其中设置了id或null

问题描述

| 我有一个ActiveRecord,Annotation,有两列:user_id和post_id,可以为null。具有空user_id和post_id的注释是\“ global \”注释,适用于所有用户的所有帖子。 我想检索与特定用户的帖子关联的所有注释以及所有全局注释。在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语法的真正好方法。最好的两个选择可能是使用绑定参数自己编写where子句:
annotations = Annotation.where(\"(user_id = ? and post_id = ?) OR (user_id is null and post_id is null)\").all
或者,您可以深入研究Arel并使用该语法来编写(请参见asciicast的Arel帖子)。 警告,
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))