2011-06-13 5 views
2

user_id와 post_id라는 두 개의 열이있는 ActiveRecord, Annotation이 있는데, null 일 수 있습니다. null user_id 및 post_id가있는 주석은 모든 사용자의 모든 게시물에 적용되는 "전역"주석입니다.레일 3 ActiveRecord where 절이 id가 설정되거나 null 인 곳

특정 사용자의 게시물 및 모든 글로벌 주석과 관련된 모든 주석을 검색하고 싶습니다. MySQL의에서 SQL 명령은 레일 3에서

select * from annotations where (user_id = 123 and post_id = 456) or (user_id is null and post_id is null) 

될하는 Annotation.where 조항으로이 코드에 가장 좋은 방법은 무엇입니까?

답변

3

불행히도 OR SQL 구문을 사용하는 것은 정말 좋은 방법이 아닙니다.

annotations = Annotation.where("(user_id = ? and post_id = ?) OR (user_id is null and post_id is null)").all 

또는 당신은 (asciicast's Arel post 체크 아웃) Arel에 뛰어과 공예 해당 구문을 사용할 수 있습니다 : 당신의 최선의 두 가지 옵션이 자신 바인딩 매개 변수를 사용하여 WHERE 절을 작성하는 아마. 경고

에서, 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)) 
관련 문제