class TbCommerce::Product < ActiveRecord::Base self.table_name = 'tb_commerce_products' scope :ordered, ->{ order('title asc') } scope :search, ->(term){ term = "%#{term}%" where('title LIKE ? OR description LIKE ?', term, term) } validates :title, :presence => true validates :title, :length => {:maximum => 255}, :uniqueness => true validates :price, :numericality => {:greater_than_or_equal_to => 0} before_save :generate_slug_from_title has_many :product_skus, :inverse_of => :product, :dependent => :destroy, :foreign_key => :tb_commerce_product_id has_many :product_option_sets, :inverse_of => :product, :dependent => :destroy, :foreign_key => :tb_commerce_product_id has_many :option_sets, :through => :product_option_sets has_many :image_links, -> { order(:sort) }, :as => :imageable has_many :images, :through => :image_links belongs_to :category, :inverse_of => :products, :foreign_key => :tb_commerce_category_id has_many :product_customizations, :inverse_of => :product, :dependent => :destroy, :foreign_key => :tb_commerce_product_id has_many :customizations, -> { order(:sort) }, :through => :product_customizations def featured_image self.image_links.each do |image_link| if image_link.is_featured return image_link.image end end end private def generate_slug_from_title if slug.blank? || title_changed? self.slug = title.parameterize end end end