Ruby on Rails将数组结果迭代到查询中

时间:2016-04-06 03:25:48

标签: ruby-on-rails ruby

以下是我的查询输出:

unless @slug == 'all'
  @city = '' if @city.blank?
  @city = @city.gsub("-", " ")
  country = Country.where("lower(name) LIKE ?", "#{@city.downcase}")
  gon.country = country
  if country.present?

  end
  if @city.present?
    @products = @products.where("lower(city) LIKE ? or lower(country) like ? or lower(state) LIKE ?", "%#{@city.downcase}%", "%#{@city.downcase}%","%#{@city.downcase}%")
    @city_obj = City.where("lower(name) LIKE ?", "%#{@city.downcase}%").first
  end
end

此处gon.country将结果返回为:

Object
countries
:
Array[2]
0
:
"california"
1
:
"san francisco" 

如何迭代countries并将其传递给@products结果?

1 个答案:

答案 0 :(得分:0)

您可以通过两种方式实现:

  1. 迭代所有国家/地区记录,然后添加类似查询。

    @product = []
    country.each do |con|
      @products << @products.where("lower(city) LIKE ? or lower(country) like ? or lower(state) LIKE ?", "%#{con.downcase}%", "%#{con.downcase}%","%#{con.downcase}%")
    end
    
  2. 您可以使用核心sql的ILIKE语法。哪个工作是这样的:

    select * from table where value ilike any (array['%foo%', '%bar%', '%baz%']);
    
    # in your case
    country_array_with_percent = country.map {|con| "%#{con}%" }
    @products.where("name ILIKE ANY ( array[?] )", country_array_with_percent)
    
  3. 您还可以使用或查询查询链接,更多详细信息here

相关问题