我有以下搜索方法:
def search(search = nil, field_search1,field_search2, field_search3,field_search4,field_search5)
if search
where("#{field_search1} LIKE ? OR #{field_search2} LIKE ? OR #{field_search3} LIKE ? OR #{field_search4} LIKE ? OR #{field_search5}LIKE ?", "%#{search}%", "%#{search}%","%#{search}%", "%#{search}%","%#{search}%")
else
where(nil)
end
end
它有效,但非常难看。试图重构它,所以我在选项哈希中传递字段名称。通过执行以下操作:
def search(search= nil, options={})
options.each do |option|
#Run the query inside here
end
It be nice if you could loop through the options and then the options that selected run the query that matches that, then when the options hash reaches the end remove the OR
from the LIKE ? OR