这涉及对连接表的验证,验证连接两侧的活动记录。它似乎没有按预期运行,允许违反验证。
我想让用户能够属于组,(或组到用户,因为它是多对多的)。但用户所在公司必须与集团公司相匹配。因此,UserGroup
看起来像这样:
class UserGroup < ActiveRecord::Base
belongs_to :user
belongs_to :group
validate :group_company_matches_user_company
private
def group_company_matches_user_company
if user.company != group.company
self.errors.add(:group, "company must match user company")
end
end
end
现在这是一个显示验证失败的测试:
test 'validation failure example' do
group = groups(:default)
user = users(:manager)
#default user and group have the same company in the DB
assert_equal user.company, group.company
#create a 2nd company
company2 = user.company.dup
assert_difference 'Company.count', 1 do
company2.save!
end
#set the group's company to the new one, verify user and group's company don't match
group.company = company2
assert_not_equal user.company, group.company
#WARNING!!! this passes and creates a new UserGroup. even though it violates
#the UserGroup validation
assert_difference 'UserGroup.count', 1 do
group.users << user
end
#What about when we save the group to the DB?
#no issues.
group.save
#this will fail. we have saved a UserGroup who's user.company != group.company
#despite the validation that requires otherwise
UserGroup.all.each do |ug|
assert_equal ug.user.company.id, ug.group.company.id
end
end