2014-02-21 64 views
0

我正在使用Rails和學習ActiveRecord,並且遇到了令人煩惱的問題。下面是我的模型的數組:檢查字符串是否包含數組中的元素

@sea_countries = ['Singapore','Malaysia','Indonesia', 'Vietnam', 'Philippines', 'Thailand'] 

而且這裏是我的ActiveRecord對象:

@sea_funding = StartupFunding.joins(:startup) 
          .where('startups.locations LIKE ?', '%Singapore%') 

我想要做的就是在「位置」列中輸入字符串匹配任何返回結果數組中的元素。我能夠將字符串匹配到數組的每個元素(如上所述),但我不知道如何迭代整個數組,以便只要有一個匹配就包含該元素。

意圖是,具有多個位置'新加坡,馬來西亞'的元素也將包含在@sea_funding中。

那麼,不要問我爲什麼'地點'被設置爲一個字符串。這只是以前的開發者所做的。

回答

1

你在你的.where過濾器中使用IN子句:

@sea_funding = StartupFunding.joins(:startup) 
          .where(["startups.locations IN (?)", @sea_countries]) 
0

@sea_countries.include?(startups.locations)

這將返回一個true,如果在初創的位置列的值可以在sea_countries陣列中找到,假的如果它不存在。

0

這可以幫你嗎?

first = true 
where_clause = nil 

sea_countries.each do |country| 
    quoted_country = ActiveRecord::Base.connection.quote_string(country) 
    if first 
    where_clause = "startups.locations LIKE '%#{quoted_country}%' " 
    first = false 
    else 
    where_clause += "OR startups.locations LIKE '%#{quoted_country}%' " 
    end 
end 

@sea_funding = StartupFunding.joins(:startup) 
          .where(where_clause) 
相關問題