在我的rails应用程序中,我需要通过表中的某个字段进行搜索,但主要的麻烦是我必须这样做: 如果我在视图A中选择了选择字段,我必须只搜索A条件,如果A和B都是A和B ... 现在我有:
控制器
@pre_oils = Oil.by_brand(params[:oilbrand]).by_oiloiliness(params[:oiloiliness]).by_structure(params[:oilstructure]).by_size(params[:oilsize])
模型
def self.by_oiloiliness(oiloiliness)
if oiloiliness
where("description LIKE ?", "%#{oiloiliness}%")
else
scoped
end
end
def self.by_brand(brand)
if brand
where("manufacturer LIKE ?", "%#{brand}%")
else
scoped
end
end
def self.by_structure(structure)
if structure
#where("structure LIKE ?", "%#{structure}%")
where("description LIKE ?", "%#{structure}%")
else
scoped
end
end
def self.by_size(size)
if size
where("capacity LIKE ?", "#{size}")
else
scoped
end
end
但是搜索非常奇怪,有一次正在工作,另一次没有....有什么不好?如何只搜索这些字段,在视图中选择哪个?
(也是ruby 1.9.3 rails 3.2.8)
也许是在所有查询中使用find获取然后拆分它们并删除重复项?
UPD
oil = Oil.brand_like(params[:oilbrand])
oil = Oil.description_like(params[:oiloiliness])
oil = Oil.description_like(params[:oilstructure])
oil = Oil.capacity_eq(params[:oilsize])
UPD2
@pre_oils = Oil.search(:manufacturer_like => params [:oilbrand],:description_like => params [:oiloiliness],:description_like => params [:oilstructure],:capacity_eq => params [ :油脂])
答案 0 :(得分:3)
对于这类事物,有很多宝石可供选择。您可以浏览meta_search,searchlogic等宝石来执行搜索。
安装meta_search
后,您可以这样做:
如果form
包含以下字段:
<%= f.text_filed :capacity_eq %>
<%= f.text_field :description_like %>
你会得到这样的参数:
params => {"description_like" => "xyz", "capacity_eq" => "21"}
Oil.search(params) #To get your results
答案 1 :(得分:0)
使用ActiveRecord
定义db抽象类
require 'active_record'
class MyDatabase < ActiveRecord::Base
self.abstract_class = true
establish_connection(
#...
:username => "",
:password => "",
:url => "")
end
定义你的表格模型
require './my_database'
class Oil < MyDatabase
self.table_name = 'oils'
end
然后使用它
Oil.where('brand LIKE ? and oiloilness LIKE ?', params[:oilbrand], params[:oiloilness])