Reputation: 1634
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.
Upvotes: 1
Views: 224
Reputation: 27779
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
Upvotes: 2