class ContactProduct < ActiveRecord::Base belongs_to :contact belongs_to :d_product validates :qte, :presence => true before_validation do self.code = self.d_product.code if self.d_product and !self.code end end