2011-06-13 58 views
2

我有一个ActiveRecord Annotation,有两列:user_id和post_id,它们可以为null。具有空user_id和post_id的注释是适用于所有用户的所有帖子的“全局”注释。Rails 3 ActiveRecord where子句其中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子句的最佳方法是什么?

回答

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通话是伪代码,不知道该怎么办“POST_ID为空” - 你可能只是通过“user_id是零和POST_ID为空”,以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))