Files
mozo-backend/app/models/product.rb
T
2014-08-27 17:14:56 +02:00

62 lines
1.9 KiB
Ruby

class Product
include SimplyStored::Couch
include ActiveModel::SerializerSupport
include Paperclip::Glue
property :name
property :code
property :price, type: Float
property :description
#belongs_to :product_category
has_and_belongs_to_many :product_categories, storing_keys: false
belongs_to :supplier # direct! category is an aid
has_many :product_orders
attr_protected :supplier_id
validates :name, presence: true
validates :supplier_id, presence: true
validates :price, presence: true, numericality: true
view :by_supplier_id_and_id, key: [:supplier_id, :_id]
after_save :persist_product_category_ids
def product_category_ids=(ids)
@product_category_ids = ids.select(&:present?)
is_dirty
end
property :image_file_name
property :image_content_type
property :image_file_size, :type => Fixnum
property :image_updated_at, :type => Time
has_attached_file :image,
url: '/system/product/:id/images/:style.:extension',
styles: {medium: '512x512>', thumb: '128x128>', large: '896x896>', small: '320x320>'},
default_url: '/assets/user/blank-pixel.png'
validates_attachment :image, content_type: {content_type: ["image/jpg", "image/jpeg", "image/png", "image/gif"]}
private
def persist_product_category_ids
return unless defined?(@product_category_ids) # Do not do anything if nothing happened to this attribute
@product_category_ids ||= []
existing_product_categories = product_categories
# do nothing if nothing has changed
return if @product_category_ids == existing_product_categories.map(&:id)
# clear removed product categories
existing_product_categories.reject{|pc| @product_category_ids.include?(pc.id) }.each{|pc| pc.remove_product(self) }
# Add product to newly added product categories
database.load(@product_category_ids - existing_product_categories.map(&:id)).each do |product_category|
product_category.add_product(self)
end
end
end