views:

38

answers:

2

hey

I have a problem, I have a Country model. where the entry in the DB is: {:name => 'United Kingdom'}

The data I have is UK instead of United Kingdom. in the other models where i search for it i have done:

country_name = "United Kingdom" if country.name == "UK"

but i have to do this all over the application and that is just bad.

So the question: How can I, in the Country model, do a search that ONLY does it for search. when it makes a query, I don't want {:name => 'UK'}.

eg. if I search for UK and the result should turn out {:name => 'United Kingdom'} NOT {:name => 'UK'}.

The solution is ok if I can just put some stupid hack in like:

name = "United Kingdom" if searchstring == "UK"
+1  A: 

You could add a customer finder method to your Country model:

class Country < ActiveRecord::Base
  def self.by_name(name)
    name == 'UK'? find_by_name('United Kingdom') : find_by_name(name)
  end
end

Then you can use Country.by_name('...') whenever you need to find a country by its name. Alternatively, if you wanted to keep the semantics of the find_by_name method:

class Country < ActiveRecord::Base
  def self.find_by_name(name)
    name = 'United Kingdom' if name == 'UK'
    where(:name => name)
  end
end

There are various variations around this. I think I would favour the second example because it presents the same API as the dynamic attribute-based finders that ActiveRecord provides i.e. find_by_XXX etc.

John Topley
is it possible to make it generic, so for all searches called with the `where(:name => 'UK')` it would work?
raus22
@raus22 I don't believe that's possible without monkey-patching ActiveRecord itself.
John Topley
Thanks for the answer, i think ill do the custom `Country.by_name` method
raus22
A: 

I think you could do it with some fairly nasty monkey patching of the ActiveRecord::Base.find method, but I don't think that is a good idea.

Where does the string 'UK' come from? User input?

I would suggest wherever that source is, put it through a common filter (perhaps an application_helper method) that converts 'UK' to "United Kingdom'.

DanSingerman