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"
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.