Rails Active Record模糊搜索数组

时间:2015-01-23 15:48:06

标签: ruby-on-rails postgresql ruby-on-rails-4 activerecord postgresql-9.2

我的Rails应用程序中有一个Postgresql数组列。据我所知,这些是长串存储的。

要搜索此列(Place#name),我在包含的模块中实现了以下方法,如下所示:

class Place
  include ActiveRecord::MetaExt::ArrayAccessor
  array_accessor :name, :category
end

并定义如下:

module ActiveRecord
  module MetaExt
    module ArrayAccessor

      module ClassMethods

        def array_accessor(*symbols)
          symbols.each do |singular|

            plural = singular.to_s.split("_").join(" ").pluralize.split(" ").join("_")

            # These two instance-level methods not super relevant to the question
            class_eval do 
              define_method("add_#{singular}") do |arg|
                send( "#{plural}=", (send(plural) + Array(arg)).uniq )
              end

              define_method(singular) do
                send(plural).first
              end
            end

            metaclass.instance_eval do 
              define_method("without_#{singular}") do
                where("? = '{}'", plural)
              end

              define_method("with_#{singular}") do |arg=nil|
                if arg.blank?
                  where.not("? = '{}'", plural)
                else
                  where("? = ANY (#{plural})", arg.is_a?(Array) ? arg.first : arg)
                end
              end
            end

          end
        end
      end

      def self.included(base)
        base.extend ClassMethods
      end
    end
  end
end

这有几个问题。

1)在with_name(字面意思,with_#{field})方法中,我只搜索给定数组中的第一个名字。我希望能够搜索包含任何这些名字的所有地方。但是,无法解决这个问题。有什么想法吗?

2)我希望能够进行模糊匹配 - 因此搜索“Barbeque Place”会占据一个名为“The Barbecue Place”的地方。看看Textacular gem,但我似乎无法将其改编为数组列。

任何想法如何使这项工作 - 特别是以一般化的方式?

0 个答案:

没有答案
相关问题