I am using rails 2.3.
How do I validate a belongs_to association field that is entered using a textbox? e.g. a blog post belongs_to a category but it is not entered using a select, but as the category name (let’s assume unique) in a textbox.
Possible errors are: wrong format, no such category in DB.
If I assign a string directly to the association it errors out with an AssociationTypeMismatch so I can’t assign to the same attribute and then use a custom before_validate method.
If I do the conversion work in the controller and add to the model’s errors collection, it is still saved (I think the errors collection is cleared before the validation is started).
How should I do this yet also use the standard error collection?
You might want to consider using a dummy text-box with javascript autocomplete functionality. Place a hidden field in the form for the ID for that association. When the JS returns a list of matches, include the ID’s, and populate the hidden ID field when an item is selected.
Otherwise, this might help. Note this is untested code.