2011-11-07 62 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}%"),但我不知道的语法去嵌套的权限。