2014-02-21 205 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) 
相关问题