1

现在我有 3 个模型

Membership:
    belongs_to :users
    belongs_to :groups

User: 
    has_many: groups, through: :memberships
    accepts_nested_attributes_for :groups
Group: 
    has_many: users, through: :memberships

然后我在做

u1 = User.new(name: "u1")
u2 = User.new(name: "u2") 
g1 = Group.new(name: "1")
u1.groups.find_or_create_by g1.attributes
u2.groups.find_or_create_by g1.attributes
u1.save
u2.save

我期望的是

Groups.all.count == 1

但它总是有'2'。

我该如何解决这个问题?

4

1 回答 1

0

如果您执行以下操作,则只会创建一个组

u1 = User.new(name: "u1")
u2 = User.new(name: "u2") 
g1 = Group.find_or_create_by_name(name: "1") #g1 is saved to db here
u1.groups << g1
u2.groups << g1
u1.save
u2.save

Group.all.count
# =>  1
于 2013-09-22T05:56:34.630 回答