[英]Check if string contains element in Array
我正在使用Rails並學習ActiveRecord,但遇到一個令人煩惱的問題。 這是我模型中的一個數組:
@sea_countries = ['Singapore','Malaysia','Indonesia', 'Vietnam', 'Philippines', 'Thailand']
這是我的ActiveRecord對象:
@sea_funding = StartupFunding.joins(:startup)
.where('startups.locations LIKE ?', '%Singapore%')
我想做的是返回一個結果,其中“位置”列中的字符串與數組中的任何元素匹配。 我能夠將字符串與Array的每個元素進行匹配(如上所述),但是我不確定如何遍歷整個Array以便只要有一個匹配項就可以包括該元素。
目的是將@sea_funding中也包含具有多個位置“ Singapore,Malaysia”的元素。
好吧,不要問我為什么將“位置”設置為字符串。 這就是以前的開發人員所做的方式。
您可以在.where
過濾器中使用IN子句:
@sea_funding = StartupFunding.joins(:startup)
.where(["startups.locations IN (?)", @sea_countries])
@sea_countries.include?(startups.locations)
如果可以在sea_countries數組中找到啟動中的locations列的值,則將返回布爾TRUE,否則返回boolean。
能為您工作嗎?
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.