Text_field_with_auto_complete

I feel I’m on a constant Yak Shave
(http://projects.csail.mit.edu/gsb/old-archive/gsb-archive/gsb2000-02-11.html)

I am playing with Auto Complete’s, due to some excellent tutorials on
railscast.com I have been making progress although hit a small stumbling
block which hope you can solve.

So I am auto completing from my Country model, which has 2 attributes
‘name’ and ‘code’

If I just wanted the ‘name’ attribute to be returned then this would
suffice in my returns js

<%= auto_complete_result @countries, :country %>

However what I actually want is ‘Country [code]’ e.g ‘Great Britain [ GB
]’

However I don’t seem to be able to get this to work - in my Country
model I have added something like this.

def code_and_country
“#{name} [ #{code} ]”
end

def code_and_country=(code_and_name)
if m = code_and_name.match(/^([^[]+)[\s(\w{2})\s]/)
code = m[2]
name = m[1]
end
end

so had hoped that I could use

<%= auto_complete_result @countries, :code_and_country %> - but I think
I am getting muddled up with methods and attributes.

So could someone be able to guide me on the correct way of doing it,
e.g. making code_and_country a fully fledged ‘attribute’ of Country or
somehow modifying the auto_complete_result helper to do the right thing?

Thanks for your help!

Sorry made a typo its

<%= auto_complete_result @countries, :name %>

not

<%= auto_complete_result @countries, :country %>

as :country is not valid!

To answer my own question - it seems text_field_with_auto_complete takes
a array of hashes, so returning

@countries = Country.search(params[:search]).map{|a| {‘code’ =>
a.code_and_country}}

<%= auto_complete_result(@countries, ‘code’) %>

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs