[英]Rails ActiveRecord .where method doesn't execute SQL query
I've written a set of Rails search methods that takes an optional parameter to define the rigor of the search. 我编写了一套Rails搜索方法,这些方法带有一个可选参数来定义搜索的严谨性。 The core method is as follows:
核心方法如下:
class Participant < ActiveRecord::Base
def self.matches(field_name, param, rigor = 'exact')
where("lower(#{field_name}) like ?", "#{param}") if rigor == 'exact'
where("lower(#{field_name}) like ?", "%#{param}%") if rigor == 'soft'
end
end
I'm getting this result: 我得到这个结果:
[1] pry(main)> >> Participant.matches('last_name', 'Goodman', 'soft')
Participant.matches('last_name', 'Goodman', 'soft')
Participant Load (5.1ms) SELECT "participants".* FROM "participants" WHERE (lower(last_name) like '%Goodman%')
=> [#<Participant:0x007fc6fecee8d0
id: 17,
first_name: "Harris",
last_name: "Goodman",
gender: 0,
birthdate: nil,
city: nil,
state_code: "CA",
email: nil,
phone: nil,
created_at: Wed, 30 Mar 2016 11:18:33 MDT -06:00,
updated_at: Wed, 30 Mar 2016 11:18:33 MDT -06:00,
created_by: 1,
updated_by: 1,
country_code: "US",
user_id: nil>]
[2] pry(main)> >> Participant.matches('last_name', 'Goodman', 'exact')
Participant.matches('last_name', 'Goodman', 'exact')
=> nil
Rails doesn't seem to be firing the SQL query when the 'exact' parameter is passed. 传递“精确”参数时,Rails似乎不会触发SQL查询。
I've also tried =
in place of like
but get the same result. 我也尝试过用
=
代替like
但是得到相同的结果。 Worked on this for over an hour with no success. 为此工作了一个多小时,但没有成功。 Any ideas would be welcome.
任何想法都将受到欢迎。
EDIT: OK, so a bit of refactoring solves the problem: 编辑:好的,所以一点重构就解决了这个问题:
def self.matches(field_name, param)
where("lower(#{field_name}) like ?", "%#{param}%")
end
def self.exact_matches(field_name, param)
where("lower(#{field_name}) like ?", "#{param}")
end
I would still like to know why this works but the more elegant earlier solution does not. 我仍然想知道为什么这样做有效,但是较优雅的早期解决方案却无效。
Every function/method returns the last evaluated value. 每个函数/方法均返回最后的评估值。 In your case it's
where("lower(#{field_name}) like ?", "%#{param}%") if rigor == 'soft'
在您的情况下,
where("lower(#{field_name}) like ?", "%#{param}%") if rigor == 'soft'
which returns nil if rigor is not 'soft'. 如果rigor不是“ soft”,则返回nil。 So adding a return should doing what you want:
因此,增加回报应该做您想要的:
def self.matches(field_name, param, rigor = 'exact')
return where("lower(#{field_name}) like ?", "#{param}") if rigor == 'exact'
where("lower(#{field_name}) like ?", "%#{param}%") if rigor == 'soft'
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.