1

I'm working with some municipality data, and it's complicated by the fact that some municipalities are technically within multiple counties—which I handled in the database as an array, like so:

[<Municipality id: 11590, name: "Wisconsin Dells", county: ["Adams", "Columbia", "Juneau", "Sauk"], latitude: nil, longitude: nil, created_at: "2012-06-06 20:05:20", updated_at: "2012-06-06 20:05:20", municipality_type: "City">]

How can I construct a call in Ruby which would return all Municipalities where county contains a given string?

Ideally, this is how I'll list all cities in a given county, for example.

EDIT: I have serialize :county in my Municipality class.

4
  • You asked how to do it in Ruby, but do you mean in Rails? or do you want a pure Ruby solution? Commented Jun 6, 2012 at 20:35
  • I guess I preferred pure Ruby... but a Rails method would be fine. I just don't want to be messing with SQL. Commented Jun 6, 2012 at 20:37
  • @jsonmklug -- but after re-reading... this is a Rails ActiveModel class, right? And you want to be able to call Municipality.for_county("Columbia") and have it return all Municipality that match, right? Commented Jun 6, 2012 at 20:46
  • @JesseWolgamott You're right—that's exactly what I'm looking for. Commented Jun 6, 2012 at 20:48

1 Answer 1

2
class Muni < ActiveRecord::Base
  def self.for_county(county)
    where %Q[county like '%"#{county}"%']
  end
end

Or, slower, but if you "just don't want to be messing with SQL":

def self.for_county(county)
  all.select { |m| m.county.include? county }
end
Sign up to request clarification or add additional context in comments.

8 Comments

why do you need second select? And where("county like ?", '%"#{county}"%')
In case you're looking for the county "foo" and there's another county called "foobar" -- the SQL will match it, but the ruby select will filter it out.
you could search with quotes, couldn't you?
Also LIKE query won't use indexes in this case, what will cause performance issues
When I say "don't want to mess with SQL", I mean I'd like it to be database-agnostic. If that's going to raise new problems, I guess I have to weigh the costs/benefits.
|

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.