2013-05-14 93 views
0

這涉及對連接表的驗證,驗證連接兩端的activerecord是否相互對立。它似乎不像預期的那樣行事,允許違反驗證。這是Rails驗證中的錯誤還是我做錯了什麼?

我想讓用戶能夠屬於組(或用戶組,因爲它是多對多的)。但用戶的公司必須與集團的公司匹配。因此,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

使用此collection << object TL:DR繞過驗證

添加一個或通過將其外鍵 鍵設置爲集合的主鍵,可以將更多對象添加到集合中。請注意,此操作 會立即觸發更新sql,而不會等待父對象上的保存或更新調用 。

相關問題