我的Organization
模型有{_ 1}}到users
。设置唯一性验证的正确方法是什么?
我有:
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
我尝试在postgres控制台中运行确切的查询,我得到0行结果。 Membership Exists (2.0ms) SELECT 1 AS one FROM "memberships" WHERE ("memberships"."user_id" = 501 AND "memberships"."organization_id" = 275) LIMIT 1
&amp; o.memberships
也显示0结果。
我唯一能想到的是u.memberships
上的唯一性验证是错误的?这有什么问题?
答案 0 :(得分:1)
m
(文档:http://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
答案 1 :(得分:0)
这里的organization_id拼写错误:
validates_uniqueness_of :user_id, :scope => :organziation_id
应该是:
validates_uniqueness_of :user_id, :scope => :organization_id