【问题标题】:How can I convert that to MetaWhere or Arel?如何将其转换为 MetaWhere 或 Arel?
【发布时间】:2011-04-23 02:17:25
【问题描述】:

考虑一个城市模型:

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

知道该字段是字符串的情况下,我如何使用 Arel 或 Metawhere 可以具有以下内容:

“名称” “居民姓名” “州名”

我想做这样的事情(不会工作):

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

那么,你的想法是什么?

真正的问题是,我该如何转换:

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

至于:

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

【问题讨论】:

  • 看来我得回到 SearchLogic 了。该死的。

标签: ruby-on-rails arel meta-where


【解决方案1】:

你应该可以像这样使用 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 的基础知识。

【讨论】:

  • 当我只有第一级可以正常工作时。但是: arel_table["residents.name"].matches... 似乎不起作用
  • 你说得对,我错过了这个要求。我已经修改了上面的代码以支持为连接表传递字段。这不是最干净的代码,但它应该可以工作。
  • arel 应该已经实现了。您不能总是指望符号,特别是当视图负责选择搜索参数时。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-27
  • 2012-11-05
  • 2013-09-23
  • 2012-10-20
  • 2017-08-21
相关资源
最近更新 更多