将 has_many 和 :belongs_to 转换为 has_many :through
我当前有一个关联,其中:
Group :has_many Members
和 Employee :belongs_to Group
但现在我希望一个 Employee 也与多个组关联。
为此,我正在考虑制作:
groupizations group_id:integerEmployee_id:integercreated_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
此代码将如何更改?我现在需要同时将数据添加到分组
中吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您想将员工添加到组中,您只需执行以下操作:
将自动创建您所称的
Groupization
记录。如果您想在关联中放入一些元数据(当您想要指定这种关系的性质时,这很常见),您可以做一些更正式的事情:由于连接模型通常在两个 ID 列上有一个唯一索引,因此请确保避免插入重复记录时可能发生的错误。这些看起来不同,具体取决于您的后端数据库,因此请进行相应的测试。您可以根据需要使用
find_or_create
。If you want to add an Employee to a Group, you would only need to do:
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: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.