0

在我的 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 获取然后拆分它们并删除重复项?

更新

 oil = Oil.brand_like(params[:oilbrand])
    oil = Oil.description_like(params[:oiloiliness])
    oil = Oil.description_like(params[:oilstructure])
    oil = Oil.capacity_eq(params[:oilsize])

更新2

@pre_oils = Oil.search(:manufacturer_like => params[:oilbrand], :description_like => params[:oiloiliness], :description_like => params[:oilstructure], :capacity_eq => params[:oilsize])

4

2 回答 2

3

For this kind of things there are many gems available. You can go through gems like meta_search, searchlogic to perform your search.

Once you install meta_search you can do like this:

When you have form with fields like following:

 <%= f.text_filed :capacity_eq %>
 <%= f.text_field :description_like %>

You will get params like this:

 params => {"description_like" => "xyz", "capacity_eq" => "21"}

 Oil.search(params)  #To get your results
于 2013-02-21T18:01:47.453 回答
0

Use ActiveRecord

define db abstract class

require 'active_record'
class MyDatabase < ActiveRecord::Base
  self.abstract_class = true
  establish_connection(
    #...
    :username => "",
    :password => "",
    :url => "")
end

define your table model

require './my_database'
class Oil < MyDatabase
  self.table_name = 'oils'
end

Then use it

Oil.where('brand LIKE ? and oiloilness LIKE ?', params[:oilbrand], params[:oiloilness])
于 2013-02-21T18:01:18.217 回答