2010-07-31 3 views
1

나는 새로운 레일 3을 좋아합니다!레일 3 : SQL 삽입 무료 쿼리

users = User.where(:name => 'Bob', :last_name => 'Brown') 

그러나 우리는

SELECT * FROM Users WHERE Age >= const AND Money > const2 

같은 것을 할 필요가있을 때 아주 멋진되지 않는 우리는

users = User.where('Age >= ? and money > ?', const, const2) 

을 사용해야합니다 :

새로운 쿼리 구문

너무 굉장 . 다음 쿼리 때문에 SQL 주입의 안전하지 않습니다 :
users = User.where('Age >= #{const} and money > #{const2}') 

내가는 C#/LINQ 버전

var users = DB.Where(u => u.Age >= const && u.Money > const2); 

레일에서 그런 일을 할 수있는 방법이 있나요 좋아?

답변

6

새로운 질의는 SQL 인젝션에 취약하지 않다된다 (인 LINQ 구문과 더 유사하다). 인수의 인용 부호는 모두 이스케이프됩니다.

레일 3 AR은 LINQ가 잠시 동안 가지고있는 지연된 실행을 얻었습니다. 이렇게하면 모든 쿼리 메서드를 연결할 수 있습니다. 유일한 시간이 에 2 개 이상을 넣을 수있는 곳은 OR입니다.

그 외에, 쿼리를 수행하는 다양한 방법이 있습니다.

Users.where('age >= ?', age).where('money > ?', money) 
Users.where('age >= ? and money > ?', age, money) 

class User < ActiveRecord::Base 
    scope :aged, lambda { |age| where('age >= ?', age) } 
    scope :enough_money, lambda { |money| where('money > ?', money) } 

    scope :can_admit, lambda { |age, money| aged(age).enough_money(money) } 
end 

Users.aged(18).enough_money(200) 
Users.can_admit(18, 200) 
+0

고마워요! 그게 내가 찾고 있던거야. – Alex

2

레일스 3에서는 이러한 선택 항목을 함께 연결할 수 있습니다. 나는 특정 구문에 최대 아니지만, 이것은 좋은 시작이다 : http://railscasts.com/episodes/202-active-record-queries-in-rails-3

기본 개념은 당신 수 체인 함께 범위 또는 조항 등 : 여기

메타 코드 :

users = User.where(:age_of_consent).where(:has_credit) 

scope :age_of_consent where("age >= ?", 18) 
scope :has_credit where("credit > ?", 10) 
3

있는 당신이 쓸 수있는 당신은 MetaWhere에 관심이있을 수 있습니다

users = User.where(:age >= const, :money > const2) 
1

당신은 당신의 쿼리에 명명 된 매개 변수의 해시를 전달할 수 있습니다 익명의 위치 매개 변수를 개선했습니다.

users = User.where('Age >= ? and money > ?', const, const2) 

은 레일

users = User.where('Age >= :const and money > :const2', {:const => const, :const2 => const2})