2010-07-31 73 views
1

我愛新的鐵路3!Rails 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); 

有沒有辦法做這樣的事情,在Rails的?

回答

6

新的查詢與軌道不容易受到SQL注入。參數中的任何引號都會被轉義。

Rails 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 2010-08-03 07:01:10

2

在Rails 3中,您可以將這些選擇鏈接在一起。我不是上來就特定的語法,但是這是一個良好的開端:http://railscasts.com/episodes/202-active-record-queries-in-rails-3

的基本概念是,你可以鏈在一起作用域或where子句等:

元代碼在這裏:

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) 

變(是爲更類似於LINQ語法)

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