我有一个Organization
has_many users
through的模型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
是错误的?这里有什么问题?