2022-07-22 18:48:28 +02:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2022-08-23 11:19:07 +02:00
|
|
|
# Product is a model for the merchandise.
|
|
|
|
# It holds data of products in the store
|
2022-07-13 15:06:46 +02:00
|
|
|
class Product < ApplicationRecord
|
2022-08-16 18:53:11 +02:00
|
|
|
extend FriendlyId
|
|
|
|
friendly_id :name, use: :slugged
|
|
|
|
|
2022-07-13 15:06:46 +02:00
|
|
|
belongs_to :product_category
|
2022-07-22 18:48:28 +02:00
|
|
|
|
2022-10-11 16:40:45 +02:00
|
|
|
has_many :machines_products, dependent: :delete_all
|
2022-09-20 15:30:44 +02:00
|
|
|
has_many :machines, through: :machines_products
|
2022-07-22 18:48:28 +02:00
|
|
|
|
2022-08-02 19:47:56 +02:00
|
|
|
has_many :product_files, as: :viewable, dependent: :destroy
|
|
|
|
accepts_nested_attributes_for :product_files, allow_destroy: true, reject_if: :all_blank
|
|
|
|
|
|
|
|
has_many :product_images, as: :viewable, dependent: :destroy
|
2022-11-22 16:31:19 +01:00
|
|
|
accepts_nested_attributes_for :product_images, allow_destroy: true, reject_if: ->(i) { i[:attachment].blank? && i[:id].blank? }
|
2022-08-02 19:47:56 +02:00
|
|
|
|
2022-08-05 15:25:51 +02:00
|
|
|
has_many :product_stock_movements, dependent: :destroy
|
|
|
|
accepts_nested_attributes_for :product_stock_movements, allow_destroy: true, reject_if: :all_blank
|
|
|
|
|
2022-08-16 18:53:11 +02:00
|
|
|
validates :name, :slug, presence: true
|
2022-10-24 12:10:42 +02:00
|
|
|
validates :slug, uniqueness: { message: I18n.t('.errors.messages.slug_already_used') }
|
2022-09-19 19:27:11 +02:00
|
|
|
validates :amount, numericality: { greater_than_or_equal_to: 0, allow_nil: true }
|
2022-09-27 15:58:59 +02:00
|
|
|
validates :amount, exclusion: { in: [nil], message: I18n.t('.errors.messages.undefined_in_store') }, if: -> { is_active }
|
2022-07-25 10:26:01 +02:00
|
|
|
|
|
|
|
scope :active, -> { where(is_active: true) }
|
2022-09-12 19:44:13 +02:00
|
|
|
|
|
|
|
def main_image
|
|
|
|
product_images.find_by(is_main: true)
|
|
|
|
end
|
2022-07-13 15:06:46 +02:00
|
|
|
end
|