class PFriend < ActiveRecord::Base belongs_to :p_customer belongs_to :p_friend_customer, :class_name => "PCustomer" attr_accessor :email validates :email, :presence => true, on: :create validates :p_customer_id, :presence => true validates :p_friend_customer_id, :presence => true has_many :p_friend_kaps has_many :kaps, :through => :p_friend_kaps before_validation do if !self.id p_friend_customer = PCustomer.where(:email => self.email).first if p_friend_customer self.p_friend_customer = p_friend_customer if self.p_customer.p_friends.where(:p_friend_customer_id => p_friend_customer.id).first or p_friend_customer.id == self.p_customer.id errors.add(:email, 'Vous avez déjà ajouté cet ami.') end else errors.add(:email, 'Aucun compte avec cet email n\'a été trouvé.') end end end after_create do PFriend.create(:p_customer_id => self.p_friend_customer_id, :p_friend_customer_id => self.p_customer_id, :email => self.p_customer.email) end def confirm self.enabled = true self.save PFriend.where(:p_customer_id => self.p_friend_customer_id, :p_friend_customer_id => self.p_customer_id).update_all(:enabled => true) end def reverse PFriend.where(:p_customer_id => self.p_friend_customer_id, :p_friend_customer_id => self.p_customer_id).first end def allow_kapsmes(kaps_day) kaps_day.kapsmes.where(:kap_id => self.kaps.ids) end end