0

UPDATE: I am so sorry. Many hours of trying to fix this problem got my brain off. Of course 'HABTM Checkboxes' railscast was the right answer to this post. As Dany said. Thank you.


I'm going into Ruby and Rails and got a problem I can't fix.

I have three tables in the database: employees, departments, and join-table departments_employees.

I use has_and_belongs_to_many relationship:

#models/employee.rb
class Employee < ActiveRecord::Base
   has_and_belongs_to_many :departments
   accepts_nested_attributes_for :departments, :allow_destroy => true
   attr_accessible :last_name, :first_name, :middle_name, :departments_attributes
end

# models/department.rb
class Department < ActiveRecord::Base
  has_and_belongs_to_many :employees
  attr_accessible :title
end

My problem is that I don't know how to create a new employee, link it to an existing department, and not create a new department at the same time.

Example:

Employee.create(:last_name => "Smith",
                :departments_attributes => [{:title => "IT"}])

But this creates both the employee and the department.

Is there any magic here to do that?

blackst0ne
  • 681
  • 6
  • 22

1 Answers1

1

One approach would be deleting

accepts_nested_attributes_for

Create a controller and views to enter departments (you can scaffold this) and use habtm to create employers and assign them departments via checkboxes.

For habtm have a look the railscast

Jesse
  • 418
  • 5
  • 8