Topic: messy association assignment using model_auto_completer

In the new and edit forms of my controllers, for some of belongs_to association fields (in this case, setting the manufacturer of a product) I'm using the model_auto_completer plugin, so that the user can start typing in the name of the manufacturer, and matches will show up in a dropdown box.

I also want to be able to create a new manufacturer if the user types a name in that doesn't exist yet. Due to the way model_auto_completer works, setting the id in a seperate field, I have only been able to do this in the controller, like this:

def set_manufacturer

  if params[:manufacturer][:name].blank? # user hasn't typed anything for the manufacturer name
    @product.errors.add 'manufacturer', 'The product must have a manufacturer'
  elsif params[:product][:manufacturer_id].blank? # User has typed in a new manufacturer
    @product.manufacturer = Manufacturer.create(:name => params[:manufacturer][:name])

  else # User has typed in an existing manufacturer
    @product.manufacturer = Manufacturer.find(params[:product][:manufacturer_id])

Which i call before or update_attributes.

I think this should probably be in the model, in a before_save filter? But as the manufacturer id/name is coming from one of two fields (params[:manufacturer][:name] or params[:product][:manufacturer_id]), one of which isn't even on the product model, I'm not sure how the best way to do it would be...?

Thanks if anyone can help smile

Last edited by mipr (2007-11-11 12:39:53)