find_or_create_by多对多

时间:2013-09-22 05:46:12

标签: ruby-on-rails

现在我有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'。

我怎么能解决这个问题?

1 个答案:

答案 0 :(得分: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