# == Schema Information # # Table name: products # # id :integer unsigned, not null, primary key # name :string(255) not null # slug :string(255) not null # description :text(65535) # description_short :text(65535) # default_category_id :integer not null # price :decimal(10, 2) not null # quantity :integer default(0), not null # chk_quantity :boolean default(FALSE), not null # active :boolean default(FALSE), not null # created_at :datetime # created_by :bigint(8) unsigned # updated_at :datetime # updated_by :bigint(8) unsigned # # products goes here class Product < ApplicationRecord extend FriendlyId include FriendlyFinder friendly_id :name, use: :slugged has_and_belongs_to_many :categories has_many :images, as: :imageable, dependent: :destroy has_many :cart_products has_many :order_products validates :name, presence: true validates :price, presence: true, format: { with: /\A\d+(?:\.\d{0,2})?\z/ }, numericality: { greater_than: 0, less_than: 1_000_000 } validates :quantity, numericality: { only_integer: true } after_update :a_update def should_generate_new_friendly_id? slug.blank? || will_save_change_to_attribute?(:name) end def default_category Category.where(id: default_category_id).first end def cover_image images.where('cover = ?', true).first end def a_update return unless saved_change_to_attribute?(:slug) # preprocess images images.each do |image| # new file from old one image.change_filename(attribute_before_last_save(:slug), slug) end end def created_name Admin.find(updated_by).description end def created_date updated_at.to_date end def max_qty chk_quantity.eql?(true) ? quantity : 10 end def categories_list categories.order(:name).pluck(:name).join(', ') end end