engine/app/models/asset_collection.rb
Jacques Crocker 8a17394223 Updating to the latest Mongoid association syntax
has_many_related => references_many
belongs_to_related => referenced_in
2010-07-30 19:15:24 -07:00

61 lines
1.2 KiB
Ruby

class AssetCollection
include Locomotive::Mongoid::Document
## fields ##
field :name
field :slug
## associations ##
referenced_in :site
embeds_many :assets
## behaviours ##
custom_fields_for :assets
liquid_methods :name, :ordered_assets
## callbacks ##
before_validation :normalize_slug
before_save :store_asset_positions!
## validations ##
validates_presence_of :site, :name, :slug
validates_uniqueness_of :slug, :scope => :site_id
## methods ##
def ordered_assets
self.assets.sort { |a, b| (a.position || 0) <=> (b.position || 0) }
end
def assets_order
self.ordered_assets.collect(&:id).join(',')
end
def assets_order=(order)
@assets_order = order
end
protected
def normalize_slug
self.slug = self.name.clone if self.slug.blank? && self.name.present?
self.slug.slugify! if self.slug.present?
end
def store_asset_positions!
return if @assets_order.nil?
@assets_order.split(',').each_with_index do |asset_id, index|
self.assets.find(asset_id).position = index
end
self.assets.clone.each do |asset|
if !@assets_order.split(',').include?(asset._id)
self.assets.delete(asset)
asset.send(:delete)
end
end
end
end