2011-11-07 44 views
2

有一個查詢失敗,因爲範圍正在運行如下查詢:'%'email'%' 內部引號導致問題,我該如何擺脫它們?Rails,從查詢中的活動記錄值附近刪除引號

user.rb (User Model) 
#it's checking a text field to see if it contains the email address 
@locations = Location.has_permission(self.email) 

location.rb (Location Model) 
scope :has_permission, lambda { |email| where("locations.permissions LIKE '%?%'",email)} 

回答

1

你的範圍應使用字符串連接來構建模式:

scope :has_permission, lambda { |email| where("locations.permissions LIKE '%' || ? || '%'",email)} 

||是字符串連接運算符在SQL所以下面:

'%' || ? || '%' 

在Ruby中,結束了相同:

'%' + email + '%' 

這是一個樣式問題,在Ruby中用百分數包裹電子郵件地址(或者用+或內插)最後得到相同的結果。也許我比許多Rails人更適合使用SQL。

+0

它似乎工作。有一個問題。 ||是什麼?做?你爲什麼有第二組內部報價? – John

+0

@John:'||'是SQL中的字符串連接運算符,因此''%'|| ? ||在Ruby中,'%'最終與''%'+ email +'%''相同。 –

+0

使用插值法對此有利嗎?還是更安全? –

2
scope :has_permission, 
     lambda { |email| where("locations.permissions LIKE ?", "%#{email}%") } 

有一種方法與AREL做到這一點,也與一個matches("%#{email}%"),但我不知道的語法去嵌套的權限。