2011-06-13 80 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))