2013-11-23 4 views
6

나는 모델에서 1 어떻게레일 (4)는 동시에

편집 여기 where in 조건을

model = (1,2,3,4) 
@posts = Post.where(category_id: id, product_model_id: model) 

내 위의 질의가 justing 복용입니다 다음 쿼리를 사용할 수있다 -1

이 코드는 작동하지만이 코드는 올바른 코드라고 생각하지 않습니까?

@posts = Post.where("category_id = ? and product_model_id in (#{model})", id) 

편집-2

나는

@posts = Post.where를 사용하는 경우 ("CATEGORY_ID =?하고 (?)에 product_model_id", ID, 모델)

invalid input syntax for integer: "15,16" 입력이

0123이므로이 오류가 발생했습니다. 다음을 수정하는 방법

select * from posts where category_id=5 and product_model_id in ('15,16')

..

+0

코드가 주입 될 수 있습니다, 당신은 할 수 없습니다 : 모델 = (1,2,3,4) 루비에서 당신은 배열을 참조하고 있습니까 ??? – bjhaid

+0

@bjhaid 내 편집 – overflow

+0

내 대답을 참조하십시오보세요 – bjhaid

답변

14
model_ids = model.split(",").map(&:to_i) 
@posts = Post.where(category_id: id, product_model_id: model_ids)</code> 

또는

model_ids = model.split(",").map(&:to_i) 
@posts = Post.where("category_id = ? AND product_model_id IN (?)", id, model_ids) 
+0

당신은 단순히'user_ids = User.all.ids' 다음'Post.where ("user_id in (?)", user_ids)'를 사용할 수 있습니다. – mtfk

2

당신은 arel를 사용할 수 있지만 난 그냥 같은 것을 할 거라고 :

@posts = Post.where("category_id = ? AND product_model_id IN (?)", id, model)

14

레일 가이드에 따라, 당신은 통과 할 수 배열을 where으로 바꾸고 IN을 사용하려는 것을 이해해야합니다. 여기에 가이드를 참조하십시오 : http://guides.rubyonrails.org/active_record_querying.html#subset-conditions

model = (1, 2, 3, 4)은 유효한 배열 구문처럼 보이지 않으므로 구문에 약간 혼란 스럽습니다.

가이드의

관련 부분 :

Client.where(orders_count: [1,3,5]) 
관련 문제