2

我目前有一个协会,其中:

Group :has_many EmployeesEmployee :belongs_to Group

但现在我希望员工也与许多组相关联。

为此,我正在考虑制作:

groupizations group_id:integer employee_id:integer created_at:datetime

这将改变 Employee 和 Group 模型:

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

我从多对多的railscasts 插曲中了解了所有这些。我唯一感到困惑的是,现在我使用以下代码创建了一个新员工:

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

这段代码将如何改变?我现在需要同时添加数据groupizations吗?

4

1 回答 1

1

如果您想将员工添加到组中,您只需执行以下操作:

@employee.groups << @group

Groupization正如您所说的,该记录将自动创建。如果您想将一些元数据放入关联中,这在您想指定这种关系的性质时很常见,您可以做一些更正式的事情:

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

由于连接模型通常在两个 ID 列上具有唯一索引,因此请务必避免在插入重复记录时可能发生的错误。根据您的后端数据库,这些看起来会有所不同,因此请进行相应的测试。您可以find_or_create根据需要使用。

于 2010-08-09T17:40:07.667 回答