Rails 动态 where 子句

问题描述

我有一个 where 子句根据表单中的 json 对象被调用。该对象具有一系列用于语言环境的布尔值,用于在给定语言环境中查找场所。

有没有比用布尔值构建长字符串更好的方法来编写一系列查询?任何在正确方向上的帮助将不胜感激。谢谢!

hard_worker.rb

def build_locales
  filters = []
  filters.push 'locale_north' if @lead.locale_north
  filters.push 'locale_south' if @lead.locale_south
  filters.push 'locale_east' if @lead.locale_east
  filters.push 'locale_west' if @lead.locale_west

  return filters
end

def build_string
  filters = build_locales
  s = ''
  filters.each_with_index do |f,i|
    s+= "#{f} = true"
    s+= " OR " if i < filters.size - 1
  end
end

def perform(lead_id)
  @venues = Venue.where(receive_all: true).or(Venue.where(build_string))
  // ... more code ...
end

解决方法

where 子句是可链接的,因此如果您需要使用这样的方法,您可以轻松地进行大量查询。

@venues = Venue.all
@venues = @venues.where(receive_all: true)
filters.each do |filter|
  @venues = @venues.or(Venue.where(filter.to_sym: true))
end
# after all of this you can just return @venues
@venues

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...