简体   繁体   中英

Ruby on Rails iterate array result into query

Following were my output from the query:

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

Here gon.country return result as:

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

How can I iterate the countries and pass it to get @products result?

You can do it in two ways :

  1. Iterate all country record and then add like query.

     @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. You can use ILIKE syntax of core sql. Which work like this :

     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) 

You can also make query chaining with or query, More details here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM