0

I'm using Rails and learning ActiveRecord and I came across a vexing problem. Here's an array in my model:

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

And here's my ActiveRecord object:

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

What I'm trying to do is to return a result where a string in the 'locations' column matches any element in the Array. I'm able to match the strings to each element of an Array (as above), but I'm not sure how to iterate over the whole Array such that the element is included as long as there's one match.

The intent is that an element with multiple locations 'Singapore,Malaysia' would be included within @sea_funding as well.

Well, don't ask me why 'locations' is set as a string. It's just the way the previous developer did it.

3 Answers 3

1

You use an IN clause in your .where filter:

@sea_funding = StartupFunding.joins(:startup)
                             .where(["startups.locations IN (?)", @sea_countries])
Sign up to request clarification or add additional context in comments.

Comments

0

@sea_countries.include?(startups.locations)

This will return a boolean TRUE if the value of the locations column in startups can be found in the sea_countries array, false if it is absent.

Comments

0

Could this work for you?

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.