Sha256: 43ac254b2ac29bad2c6759d251da3ac43a798f70becd3f1e4d6b0f1fa94032b1

Contents?: true

Size: 1.85 KB

Versions: 15

Compression:

Stored size: 1.85 KB

Contents

class SpudPostCategory < ActiveRecord::Base
	searchable
	has_and_belongs_to_many :posts,
		:class_name => 'SpudPost',
		:join_table => 'spud_post_categories_posts',
		:foreign_key => 'spud_post_category_id'
	has_many :children, :class_name => 'SpudPostCategory', :foreign_key => 'parent_id'
	
	validates_presence_of :name, :url_name
	validates_uniqueness_of :name, :url_name
	validate :parent_is_valid
	before_validation :set_url_name

	before_destroy :update_child_categories

	scope :top_level, where(:parent_id => 0).order('name asc')

	attr_accessible :name, :url_name, :parent_id

	def self.grouped
		return all.group_by(&:parent_id)
	end

	# Returns an array of categories in order of heirarchy
	# 	:fitler Filters out a category by ID, and all of its children
	#   :value Pick an attribute to be used in the value field, defaults to ID
	def self.options_for_categories(config={})
		collection = config[:collection] || self.grouped
		level 		 = config[:level] 		 || 0
		parent_id  = config[:parent_id]  || 0
		filter 		 = config[:filter] 		 || nil
		value      = config[:value]			 || :id
		list 			 = []
		if collection[parent_id]
			collection[parent_id].each do |c|
				if c.id != filter
					list << [level.times.collect{ '- ' }.join('') + c.name, c[value]]
					list += self.options_for_categories({:collection => collection, :parent_id => c.id, :level => level+1, :filter => filter, :value => value})
				end
			end
		end
		return list
	end

	def posts_with_children
		# TO DO: This should return all posts that belong to the instance category and all its child categories
		return posts
	end

	private

	def set_url_name
		self.url_name = self.name.parameterize
	end

	def parent_is_valid
		if parent_id == self.id
			errors.add :base, 'Category cannot be its own parent'
		end
	end

	def update_child_categories
		self.children.update_all(:parent_id => self.parent_id)
	end
end

Version data entries

15 entries across 15 versions & 1 rubygems

Version Path
spud_blog-0.8.18 app/models/spud_post_category.rb
spud_blog-0.8.17 app/models/spud_post_category.rb
spud_blog-0.8.16 app/models/spud_post_category.rb
spud_blog-0.8.15 app/models/spud_post_category.rb
spud_blog-0.8.14 app/models/spud_post_category.rb
spud_blog-0.8.13 app/models/spud_post_category.rb
spud_blog-0.8.12 app/models/spud_post_category.rb
spud_blog-0.8.11 app/models/spud_post_category.rb
spud_blog-0.8.8 app/models/spud_post_category.rb
spud_blog-0.8.7 app/models/spud_post_category.rb
spud_blog-0.8.6 app/models/spud_post_category.rb
spud_blog-0.8.5 app/models/spud_post_category.rb
spud_blog-0.8.4 app/models/spud_post_category.rb
spud_blog-0.8.3 app/models/spud_post_category.rb
spud_blog-0.8.2 app/models/spud_post_category.rb