one of my model belongs_to another (zip codes). i would like to let the user insert the zip code in a text field instead of the select menu generated by the collection_select. No new zip code should be created and the code should be validated (it should be in the list of valid code). How can this be achieved?
one of my model belongs_to another (zip codes). i would like to let the user insert the zip code in a text field instead of the select menu generated by the collection_select. No new zip code should be created and the code should be validated (it should be in the list of valid code). How can this be achieved?
You want an auto completing text field. There are some plugins out there that can do this and associate it to the other model automatically. Here's one:
http://model-ac.rubyforge.org/svn/trunk/vendor/plugins/model_auto_completer
You can also roll your own using a prototype/jquery auto completing plugin...
-philip
You might want to check out:
http://github.com/Erol/nested_reference
Assuming your models were Person and ZipCode, and ZipCode has a field called 'code':
class Person belongs_to :zip_code validates_presence_of :zip_code, :message => 'Zip Code can't be empty or was not found in the list of valid codes.'
accepts_nested_reference_and_attributes_for :zip_code, :code, :required => true end
View:
form_for @person do |p| p.text_field :name p.fields_for :zip_code |zc| zc.text_field :code end end
Controller:
person.update_attributes(:person) # Nothing special needs to be done. person.zip_code_id will be set depending on the zip code the user filled in.
You can add auto-completion in your view. I'd recommend jQuery Autocomplete.
Hope this helps,
Sorry for the garbled code. Here's a pastie link instead:
i tried the plugin you suggested, which seems exactly what i'm looking for. but i got stuck:
my user model has this line belongs_to :cap_residenza, :class_name => 'Cap' and i added
accepts_nested_reference_and_attributes_for :cap_residenza, :codice, :required => true
in the form view i added this: <% f.fields_for :cap_residenza do |fr| %> <%= fr.label :cap %> <%= fr.text_field :codice %> <% end %> but nothing appears. if i change 'cap_residenza' with anything else the form shows up correctly (but it doesn't work, everything else is looking for cap_residenza i suppose). what am i missing?
thank you
Does it work if you remove the accepts_nested_reference_and_attributes_for line? If no, could you send the models and form snippets (with the form_for block) as a pastie?