Ōkami X Oukarin
Ōkami X Oukarin

Reputation: 435

Validate on update if attribute change in Rails

I have a table called: Invitation with cols: name, email

User table have 2 cols: email, secondary_email

User A wanna invite user B to be friend. If A already invited B via email, then if A invite B again via secondary_email, it throw error: already invited via another email. Wrote the validate and work fine.

The problem is: if i update some invition already existed with B's secondary_email, it not throw any error.

validate :is_already_invited?,
       on: :update,
       if: :email_changed?

validate :is_already_invited?,
       on: :create

def is_already_invited?
  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

how to make model validate on update if email changed.

Tks

Upvotes: 2

Views: 8970

Answers (1)

Krishna Vyas
Krishna Vyas

Reputation: 285

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

Upvotes: 5

Related Questions