Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/assembly/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 检查字符串是否包含数组中的元素_Ruby On Rails_Activerecord - Fatal编程技术网

Ruby on rails 检查字符串是否包含数组中的元素

Ruby on rails 检查字符串是否包含数组中的元素,ruby-on-rails,activerecord,Ruby On Rails,Activerecord,我在使用Rails和学习ActiveRecord时遇到了一个棘手的问题。我的模型中有一个数组: @sea_countries = ['Singapore','Malaysia','Indonesia', 'Vietnam', 'Philippines', 'Thailand'] 这是我的ActiveRecord对象: @sea_funding = StartupFunding.joins(:startup) .where('startu

我在使用Rails和学习ActiveRecord时遇到了一个棘手的问题。我的模型中有一个数组:

@sea_countries = ['Singapore','Malaysia','Indonesia', 'Vietnam', 'Philippines', 'Thailand']
这是我的ActiveRecord对象:

@sea_funding = StartupFunding.joins(:startup)
                             .where('startups.locations LIKE ?', '%Singapore%')
我要做的是返回一个结果,其中“locations”列中的字符串匹配数组中的任何元素。我能够将字符串与数组的每个元素进行匹配(如上所述),但我不确定如何迭代整个数组,以便只要有一个匹配项,就包含该元素

其目的是将具有多个地点“新加坡、马来西亚”的要素也包括在@sea_资金中


好吧,不要问我为什么“位置”被设置为字符串。这正是以前的开发人员所做的。

您在
中使用IN子句。其中
过滤器:

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

@sea\u国家。包括?(初创企业。地点)


如果startups中locations列的值可以在sea_countries数组中找到,则返回布尔值TRUE;如果没有,则返回布尔值false。

这对您有用吗

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)