0

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}%" }

4

1 回答 1

0

你应该可以像这样使用 Arel。

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

有一个Railscast很好地解释了在 Rails 3 中使用 Arel 的基础知识。

于 2011-04-23T03:15:58.407 回答