views:

66

answers:

1

I have a current association where:

Group :has_many Employees and Employee :belongs_to Group

but now I want an Employee to be associated to many Groups as well.

For this purpose I am thinking of making:

groupizations group_id:integer employee_id:integer created_at:datetime

This will change Employee and Group models:

class Groupizations < ActiveRecord::Base
   belongs_to  :employee
   belongs_to  :group
end

class Group < ActiveRecord::Base
   has_many    :groupizations
   has_many    :employees, :through => categorizaitons
end

class Employee < ActiveRecord::Base
   has_many    :groupizations
   has_many    :groups, :through => categorizaitons
end

I understand all of this from railscasts episode on Many-to-Many. Only thing I am confused about is that right now I create a new Employee with following code:

  def create
    @employee = Employee.new(params[:employee])
    if @employee.save
      flash[:notice] = "Successfully created employee."
      redirect_to @employee
    else
      render :action => 'new'
    end
  end

how will this code change? Do I need to add data into groupizations at the same time now?

A: 

If you want to add an Employee to a Group, you would only need to do:

@employee.groups << @group

The Groupization record, as you've called it, will be created automatically. If you want to put some meta-data in the association, which is common when you want to specify the nature of this relationship, you could do something more formal:

@employee.groupizations.create(
  :group => group,
  :badge_number => 'F920'
)

As join models typically have a unique index on the two ID columns, be sure to rescue from errors that may occur when inserting a duplicate record. These look different depending on your back-end DB, so test accordingly. You can use find_or_create as needed.

tadman