Advertisement
Secretprtay

Untitled

Jan 30th, 2022
1,142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rails 1.92 KB | None | 0 0
  1. class Product < ApplicationRecord
  2.   belongs_to :category
  3.   has_rich_text :description
  4.   has_many_attached :images
  5.  
  6.   enum sex:   %i[male female other]
  7.   enum size:  %i[xxs xs s m l xl xxl]
  8.   enum color: %i[black white grey red orange blue violet green sky]
  9.  
  10.   enum brand: {
  11.                 PM: 'Puma',
  12.                 AD: 'Adidas',
  13.                 NB: 'New Balance',
  14.                 NK: 'Calvin Klein',
  15.                 LV: 'Levi`s'
  16.               }
  17.   # BRAND_LIST = brand.values
  18.  
  19.   enum type: { JN: 'Jeans',
  20.                TS: 'T-shirt',
  21.                SN: 'Sneakers',
  22.                BT: 'Boots',
  23.                FL: 'Flats',
  24.                SD: 'Sandals',
  25.                CL: 'Clogs'
  26.              }
  27.  
  28.   validates :name, presence: true, length: { maximum: 150 }
  29.   validates :sku, length: { maximum: 12 }
  30.   validates :discount, inclusion: { in: 0...100 }
  31.   validates :description, presence: true, length: { maximum: 500 }
  32.   validates :brand, inclusion: { in: brands.stringify_keys.keys,
  33.                                   message: 'not included in a specific list!' }
  34.   validates :product_type, inclusion: { in: types.stringify_keys.keys,
  35.                                   message: 'not included in a specific list!' }
  36.   validates :sex, inclusion: { in: sexes.stringify_keys.keys,
  37.                                   message: 'not included in a specific list!' }
  38.   validates :size, inclusion: { in: sizes.stringify_keys.keys,
  39.                                   message: 'not included in a specific list!' }
  40.   validates :color, inclusion: { in: colors.stringify_keys.keys,
  41.                                   message: 'not included in a specific list!' }
  42.  
  43.   after_create_commit :generate_sku
  44.  
  45.   def generate_sku
  46.     sku_id = format('%04d', self.id)
  47.     size  = Product::sizes[self.size]
  48.     color = Product::colors[self.color]
  49.     sku = "#{brand}#{product_type}-#{sku_id}-#{size}#{color}"
  50.  
  51.     self.update(sku: sku)
  52.   end
  53. end
  54.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement