Update in a has_many: though association.

Hello. I need an advice to find a solution on creating a new has_many :through association on a existing model. I have:

Company   has_many :managements, :dependent => :destroy   has_many :managers, :through => :managements

Manager   has_many :managements, :dependent => :destroy   has_many :companies, :through => :managements

With the command link_to "Add manager", new_company_manager_url(@company), :class => "btn", :remote => true

I display the manager form, create a new manager associated to the company and create a new management. In manager controller:

def create     @company = Company.find(params[:company_id])     @manager = Manager.new(params[:manager])     add_management     @manager.save     respond_with @manager end

private   def add_management     profile = params[:manager][:profile]     profile.delete_if { |v| v.empty? }     profile.each do |prof|       @manager.managements.build(:profile => prof, :company => @company)     end   end

If the manager exists I only need to create a new management, so in the manager new action I've put:

def new     @company = Company.find(params[:company_id])     @manager = Manager.find_or_initialize_by_fiscal_code(params[:fiscal_code])     respond_with(@manager) end

If the manager does not exists I create a new one and a new management like showed before. But, if the manager exists the form action is to update manager. I'm searching for a solution to only create a new management without updating manager.

Why can't you do what you want in the update action? If the details of the manager record have not changed then the update will do nothing.

Colin

Uhm it sounds strange to me creating a new management association in the manager update action. I mean update only to to update manger attributes. Perhaps I'm wrong.

If you want to do it in the manager controller then update is the correct action as changing the managements that it has is effectively an update, even though this does not involve editing the manager record itself. The other alternative is to put it in the create action of the management controller. It is up to you which seems most appropriate.

Colin