55 lines
1.3 KiB
Ruby
55 lines
1.3 KiB
Ruby
# 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
|