如何使 has_many 关联变得独一无二?
这是一个例子:
Class Store < ActiveRecord::Base
has_many :employees
end
现在,当我像这样创建一个员工:
employee = Employee.new(attributes)
然后像这样创建两个商店:
store1 = Store.new(employees: [employee])
store2 = Store.new(employees: [employee])
它将员工上的 store_id 更改为商店 2,从而摆脱与 store1 的关联。如何确保一间商店只能分配一名员工?
Here's an example:
Class Store < ActiveRecord::Base
has_many :employees
end
Now when I create an employee like so:
employee = Employee.new(attributes)
and then two stores like so:
store1 = Store.new(employees: [employee])
store2 = Store.new(employees: [employee])
it changes the store_id on the employee to store 2, getting rid of the association with store1. How do I make sure that only one employee can be assigned to one store?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试使用 .build 语法:
因此,在创建操作中(我假设这是来自员工新操作,并且商店已经创建。)执行如下操作:
还要确保您的员工中有一个 own_to模型。
Try using .build syntax:
So in the create action (I'm assuming this is coming from an employee new action, and that the stores have already been created.) do something like this:
Also be sure you have a belongs_to in your employees model.