这是Rails验证中的错误还是我做错了什么?

时间:2013-05-14 19:31:54

标签: ruby-on-rails validation activerecord

这涉及对连接表的验证,验证连接两侧的活动记录。它似乎没有按预期运行,允许违反验证。

我希望允许用户能够属于群组(或群组到用户,因为它是多对多的)。但是用户的公司必须与该集团的公司相匹配。因此,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

1 个答案:

答案 0 :(得分:1)

使用此collection << object TL:DR绕过验证

  

通过设置外部对象,将一个或多个对象添加到集合中   集合主键的键。注意这个操作   立即触发更新sql而不等待保存或更新调用   在父对象上。