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?