以下是一个例子:
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的关联。如何确保只能将一名员工分配到一个商店?
答案 0 :(得分:2)
尝试使用.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])
还要确保您的员工模型中有belongs_to。