Topic: Help with DRY up

I am a newbie trying to DRY up my first application. Going well accept this annoying item (simplified down to problematic code) ...

Original code:

    business_attributes = params[...] # values from a form in a view
    business_application = BusinessApplication.find(..) # id from view
    business_area = BusinessArea.create! business_attributes
    business_application.business_areas << business_area unless @business_application.nil?
    business_application.save

Now refactored to make more generic and not tied to any particular models (so I can add as an ApplicationController method and become part of a acts_as helper). This code is part of a set of methods that are used 10's of times across various controllers (the rest successfully DRY'd). target and source have a habtm relationship. The new code is as follows:

    target_model_class = Object.const_get(target) # target == 'business_areas' - passed as argument
    source_model_class = Object.const_get(source) # source == 'business_applications' - passed as argument

    attributes = params[...] # values from a form in a view
    source_instance = source_model_class.find(...) # id from view
    target_instance = target_model_class.create! attributes
    source_instance.method(target) << target_instance unless source_instance.nil?
    source_instance.save


But gets the following error complaining << method does not exist in line 7 above:

undefined method `<<' for #<Method: BusinessApplication#business_areas>

Have tried using #push instead of << method but with same error. Also tried some poorly constructed #call methods too. I know I'm probably doing something completely wrong around the use of #method.

Any help?

Thanks!

Martyn.

Re: Help with DRY up

Jean Francois corrected my mistake (copied from Ruby Forum http://www.ruby-forum.com/topic/137023) ...

Jean-Fran&#65533;ois wrote:

>   source_instance.save
>
> But gets the following error complaining << method does not exist:
>
>   undefined method `<<' for #<Method:
> BusinessApplication#business_areas>


You don't need to use #method method : you don't want to
manipulate a Method object but you just want to send a message
whose name is an association.

You should look at : source_instance.send(target)

   -- Jean-Fran&#65533;ois.

This worked thank you.