Rails 3 ActiveRecord where子句设置的子句或null
我有一个ActiveRecord,Annotation,有两列:user_id和post_id,可以为null。 具有null user_id和post_id的注释是适用于所有用户的所有post的“全局”注释。
我想检索与特定用户的post和所有全局注释相关的所有注释。 在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的Arelpost )。
警告 , or
调用中的所有内容都是伪代码,不知道怎么做’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))