如果Rails中的属性更改,则在更新时进行验证

时间:2016-10-07 09:03:58

标签: ruby-on-rails

我有一个名为:邀请cols:name,email

用户表有2个列:email,secondary_email

用户A想邀请用户B成为朋友。 如果A已经通过电子邮件邀请了B,那么如果A再次通过secondary_email邀请B,则会抛出错误:已经通过另一封电子邮件邀请了。 写完验证并正常工作。

问题是:如果我更新了B的secondary_email已经存在的一些邀请,它不会抛出任何错误。

UIView *superview = scrollView;

while (![superview isKindOfClass:[UICollectionViewCell class]]) {

    superview = superview.superview;
}

UICollectionViewCell *cell = (UICollectionViewCell *)superview;
NSIndexPath *indexPath = [self.collectionView indexPathForCell:cell];

NSLog(@"IndexPath: %@", indexPath);

如果电子邮件发生更改,如何在更新时进行模型验证。

韩国社交协会

1 个答案:

答案 0 :(得分:1)

validate :is_already_invited?, on: :update

    def is_already_invited?
        if email_changed?
          user = User.where(secondary_email: self.email).first
          if user
            self.inviter.friendships.each do |friendship|
              friendship.errors[:email] = "is already invited under different email address." if (friendship.email = user.email)
            end
          end
        end
    end