[英]Rails ActiveRecord .where method doesn't execute SQL query
我編寫了一套Rails搜索方法,這些方法帶有一個可選參數來定義搜索的嚴謹性。 核心方法如下:
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
我得到這個結果:
[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似乎不會觸發SQL查詢。
我也嘗試過用=
代替like
但是得到相同的結果。 為此工作了一個多小時,但沒有成功。 任何想法都將受到歡迎。
編輯:好的,所以一點重構就解決了這個問題:
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
我仍然想知道為什么這樣做有效,但是較優雅的早期解決方案卻無效。
每個函數/方法均返回最后的評估值。 在您的情況下, where("lower(#{field_name}) like ?", "%#{param}%") if rigor == 'soft'
如果rigor不是“ soft”,則返回nil。 因此,增加回報應該做您想要的:
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.