1

所以我有很多具有很多属性的东西。我正在快速搜索,用户在文本框 params[:q] 中输入了一个术语,然后我搜索该批次的每个字段以查看它是否匹配。我还想检查他们的属性,如果属性匹配,并且只返回地段。

我做到了,像这样

    if params[:q]
        @property_lots = []
        @lots.each do |lot|
            @property_lots << lot if lot.properties.where(["name LIKE :query OR value LIKE :query", :query => "%#{params[:q]}%"]).any?
        end

        @lots = @lots.where(["number LIKE :query OR title LIKE :query OR description LIKE :query OR position LIKE :query OR notes LIKE :query OR notes LIKE :query OR buyer_id LIKE :query OR 
            display_type LIKE :query OR status LIKE :query", :query => "%#{params[:q]}%"])

        @lots = @lots.merge(@property_lots)
        @lots.uniq!
    end

这样做的问题是它将 activerecord:relation 变成了一个数组,这会破坏我的分页、稍后添加的范围以及我的重新排序。有没有办法在不创建数组的情况下做到这一点?

4

3 回答 3

2

您可以在模型中定义一个方法来使用关键字进行搜索:

def self.search_strategy(string)
  string = "%#{string}%"
  scope = self.includes(:properties)
  scope = scope.where("lots.number ILIKE :q OR lots.title ILIKE :query OR lots.description ILIKE :query OR lots.notes ILIKE :q OR lots.position ILIKE :q OR ILIKE lots.buyer_id ILIKE :q OR lots.display_type ILIKE :q OR lots.status ILIKE :q OR properties.name ILIKE :q OR properties.value ILIKE :q", q: string)
  scope
end

并在您的控制器中像这样使用它:

if params[:q]
  @lots = Lot.search_strategy(params[:q])
end

灵活的版本

def self.search_strategy(string)
  string = "%#{string}%"
  conditions = []
  ['number', 'title', 'description', 'notes', 'position', 'buyer_id', 'display_type', 'status'].each do |column_name|
    conditions << "lots.#{column_name} ILIKE :q"
  end
  ['name', 'value'].each do |column_name|
    conditions << "properties.#{column_name} ILIKE :q"
  end
  conditions = conditions.join(' OR ')
  scope = self.includes(:properties)
  scope = scope.where(conditions, q: string)
  scope
end

使用上面的版本,您可以轻松添加/删除要搜索的列;-)

于 2013-09-20T15:28:10.093 回答
0

这是一个“请原谅我即将要做的可怕事情”的答案。

在你之后@lots.uniq!

@lots = Lot.find(@lots.map(&:id))

Rails 的身份映射缓存可能不会太糟糕,但希望有人有更好的东西!

看起来身份映射在 Rails 4 中消失了......哦,好吧。:)

于 2013-09-20T15:22:35.640 回答
0
if params[:q]   
 @lots = @lots.joins("LEFT JOIN properties ON properties.lot_id = lots.id").where(["lots.number LIKE :query OR lots.title LIKE :query OR lots.description LIKE :query 
                    OR lots.notes LIKE :query OR lots.display_type LIKE :query OR lots.status LIKE :query OR properties.name LIKE :query OR properties.value LIKE :query", :query => "%#{params[:q]}%"])``
end

左连接修复了它

于 2013-09-20T20:30:52.443 回答