ruby-on-railsarelmeta-where

How can I convert that to MetaWhere or Arel?


Consider a City Model having:

  def self.search(field, search)
    if search
      where("#{field} LIKE ?", "%#{search}%")
    else
      scoped
    end
  end

How can I use Arel or Metawhere in that situation knowing that field is a String can have anything like:

"name" "residents.name" "state.name"

I want to do something like that (will not work):

  def self.search(field, search)
    if search
       where(field =~ "%#{search}%")
    else
      scoped
    end
  end

So, what are your thoughts?

The real question is, how can I convert that:

"residents.name LIKE '#{value}%'"

To that:

:residents => { :name =~ "#{value}%" }


Solution

  • You should be able to use Arel like this.

    def self.search(field, search)
      if search
        if field =~ /\./ # table and field
          table, field = field.split('.')
          arel_join = table.singularize.camelize.constantize.arel_table
          joins(table.to_sym).where(arel_join[field].matches("%#{search}%"))
        else
          where(Resource.arel_table[field].matches("%#{search}%"))
        end
      else
        scoped
      end
    end
    

    There's a Railscast that does a good job of explaining the basics of using Arel in Rails 3.