开发者

How do you make a has_many association unique?

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开发者_C百科 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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜