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.