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
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 に答える
0

これが「私がやろうとしている恐ろしいことを許してください」という答えです.

あなたの後@lots.uniq!

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

Rails の ID マップのキャッシングにより、これはそれほどひどいものではないかもしれませんが、誰かがもっと良いものを持っていることを願っています!!

Rails 4 では ID マップがなくなったようです...まあ。:)

于 2013-09-20T15:22:35.640 に答える