0

我有一个Organizationhas_many usersthrough的模型memberships。设置唯一性验证的正确方法是什么?

我有:

class Organization < ActiveRecord::Base
  has_many :memberships
end

class Membership < ActiveRecord::Base
  belongs_to :user
  belongs_to :organization
  validates_presence_of :organization_id
  validates_presence_of :user_id
  validates_uniqueness_of :user_id, :scope => :organization_id
end

class User < ActiveRecord::Base
  has_many :memberships
end

当我尝试创建会员时:

o = Organization.find(275)
u = User.find(505)
m = o.memberships.new(user_id: u.id)
m.save

我得到:

Membership Exists (2.0ms)  SELECT 1 AS one FROM "memberships" WHERE ("memberships"."user_id" = 501 AND "memberships"."organization_id" = 275) LIMIT 1

我尝试在 postgres 控制台中运行确切的查询,我得到 0 行结果。o.memberships&u.memberships也显示 0 个结果。

我唯一能想到的是唯一性验证memberships是错误的?这里有什么问题?

4

2 回答 2

1

(文档:httpm ://apidock.com/rails/ActiveRecord/Base/create/class)返回的已经保存,所以下一个调用没用o.memberships.create()save

o = Organization.find(275) 
u = User.find(505)
m = o.memberships.create(user_id: u.id)
m.save
于 2013-06-10T08:49:08.480 回答
0

此处的 organization_id 拼写错误:

validates_uniqueness_of :user_id, :scope => :organziation_id

它应该是:

validates_uniqueness_of :user_id, :scope => :organization_id
于 2013-06-10T08:45:43.547 回答