Is this a bug in Rails validations or am I doing something wrong? -


this involves validations on join table, validating activerecord on either side of join against each other. seems not behave expected, allowing violation of validation.

i want allow users able belong groups, (or groups users, it's many-to-many). user's company must match group's company. hence, usergroup looks this:

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 

now here test showing failure of validation:

test 'validation failure example'     group = groups(:default)     user = users(:manager)      #default user , group have same company in db     assert_equal user.company, group.company      #create 2nd company     company2 = user.company.dup     assert_difference 'company.count', 1       company2.save!     end      #set group's company new one, verify user , group's company don't match     group.company = company2         assert_not_equal user.company, group.company      #warning!!! passes , creates new usergroup. though violates     #the usergroup validation     assert_difference 'usergroup.count', 1       group.users << user     end      #what when save group db?     #no issues.     group.save      #this fail. have saved usergroup who's user.company != group.company     #despite validation requires otherwise     usergroup.all.each |ug|       assert_equal ug.user.company.id, ug.group.company.id     end   end 

using collection << object tl:dr bypasses validation

adds 1 or more objects collection setting foreign keys collection’s primary key. note operation instantly fires update sql without waiting save or update call on parent object.


Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -