Hello.
I am using auto-complete fields in my application and I found myself
duplicating a lot of code.
Here is a sample of what I have in my view:
<%= text_field_with_auto_complete :model,
:codeA,
:maxlength => 35,
:size => 35,
:frequency => 0,
:style => 'off',
:autocomplete => 'off' -%>
<div class=auto_complete id=model_codeA_auto_complete
style=‘display: none’>
<%= text_field_with_auto_complete :model,
:codeB,
:maxlength => 35,
:size => 35,
:frequency => 0,
:style => 'off',
:autocomplete => 'off' -%>
<div class=auto_complete id=model_codeB_auto_complete
style=‘display: none’>
The models all look the same too:
class ModelA < ActiveRecord::Base
self.table_name = ‘modela’
def self.get_codes
return ModelA.find(
:all,
:select => ‘code’,
:order => ‘code’
).collect {|row| row.code}
end
end
class ModelB < ActiveRecord::Base
self.table_name = ‘modelb’
def self.get_codes
return ModelB.find(
:all,
:select => ‘code’,
:order => ‘code’
).collect {|row| row.code}
end
end
: : : and so on…
The only thing that changes in the methods is the name of the model,
as you can see.
In my controller I have another set of methods to retrieve the
necessary information for the drop downs and auto-completes:
def auto_complete_for_codeA
@codes = ModelA.get_codes
render_options(@codes, params[:model][:codeA])
end
def auto_complete_for_codeB
@codes = ModelB.get_codes
render_options(@codes, params[:model][:codeB])
end
: : : and so on…
‘render_options’ is another method that I got DRY enough and I don’t
need to make any changes as of right now. It finds matching values in
@codes based on the second parameter value, then renders a partial.
As you can see there is a lot of duplication in all of this and I
would like to make it as DRY as possible. The only thing I think can
be done is to to modify all those controller methods by soft-coding
somehow the name of the Model to be used and get something like this:
def auto_complete_for_codeA
render_options(:ModelA, params[:model][:codeA])
end
def auto_complete_for_codeB
render_options(:ModelB, params[:model][:codeB])
end
Then render_option would do all the grunt work converting :myModelx to
a usable model name. If you know how to make this happen and/or have
better ideas please let me know.
Thanks a lot.
Pepe