2011-10-05 6 views
1

내가 지금처럼 내 조건을 구축하기 위해 노력하고있어 건물 :레일 - 조건문

conditions = {} 
conditions[:doors] = 4 
conditions[:type] = "sedan" 

Cars.find(:all, :conditions=>conditions) 

어떻게 'LIKE'조건 내 조건에 추가합니다 :

conditions[:color] NOT LIKE '%black%' 

답변

2

당신은 레일이있는 경우 다음

records = Car.where(:doors => 4, :type => "sedan") 
records = records.where("color NOT LIKE ?", "%black%") 

그러나 당신은 여전히 ​​레일 2.3을 사용하는 경우 : 조회 건물의 일부 새로운 AREL 구문을 사용하는 것을 고려 3+ 구문은 다음과 같습니다.

clauses = ["doors = ?", "type = ?"] 
conditions = [4, 'sedan'] 

if some_reason 
    clauses << "color NOT LIKE ?" 
    conditions << "%robert%" 
end 



Cars.find(:all, :conditions => [clauses.join(" AND"), *conditions]) 

AREL 구문보다 훨씬 성가심이 듭니다.

이 구문의 부작용은 ActiveRecord가 ?을 대체 할 때 SQL 주입을위한 입력을 위생 처리한다는 것입니다.