如何使 has_many 关联变得独一无二?

发布于 2024-11-28 15:42:52 字数 386 浏览 1 评论 0原文

这是一个例子:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

孤芳又自赏 2024-12-05 15:42:52

尝试使用 .build 语法:

因此,在创建操作中(我假设这是来自员工新操作,并且商店已经创建。)执行如下操作:

#this is the id of whatever store... maybe its a nested resource so it would be something like
#@store = Store.find(params[:store_id])
@store = Store.find(id)
@employee = @store.employees.build(params[:employee])

还要确保您的员工中有一个 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:

#this is the id of whatever store... maybe its a nested resource so it would be something like
#@store = Store.find(params[:store_id])
@store = Store.find(id)
@employee = @store.employees.build(params[:employee])

Also be sure you have a belongs_to in your employees model.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文