0

これには、結合テーブルの検証が含まれ、結合の両側のアクティブ レコードを相互に検証します。期待どおりに動作しないようで、検証に違反する可能性があります。

ユーザーがグループに所属できるようにしたい (または多対多であるため、グループからユーザーへ)。ただし、ユーザーの会社はグループの会社と一致する必要があります。したがって、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
4

1 に答える 1

1

このcollection << objectTL:DR を使用すると、検証がバイパスされます

外部キーをコレクションの主キーに設定して、1 つ以上のオブジェクトをコレクションに追加します。この操作は、親オブジェクトの保存または更新の呼び出しを待たずに update sql を即座に起動することに注意してください。

于 2013-05-14T20:31:20.300 に答える