/
category.rb
68 lines (55 loc) · 1.9 KB
/
category.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
class Category < ActiveRecord::Base
acts_as_nested_set :scope => :section_id
has_permalink :title, :url_attribute => :permalink, :sync_url => true, :only_when_blank => true, :scope => :section_id
translates :title
belongs_to :section, :foreign_key => 'section_id'
has_many :contents, :through => :categorizations, :source => :categorizable, :source_type => 'Content'
has_many :categorizations, :dependent => :delete_all
before_save :update_path
validates_presence_of :section, :title
validates_uniqueness_of :permalink, :scope => :section_id
def owners
owner.owners << owner
end
def owner
section
end
def all_contents
section.class.to_s == 'Album' ? scope_by_set : scope_by_content
end
protected
def scope_by_set
scope = Photo.scoped({})
scope = scope.scoped :include => :sets, :conditions => ["categories.lft >= ? AND categories.rgt <= ?", lft, rgt]
scope
end
def scope_by_content
scope = Content.scoped({})
scope = scope.scoped :include => :categories, :conditions => ["categories.lft >= ? AND categories.rgt <= ?", lft, rgt]
scope = scope.scoped :conditions => ["contents.type = ?", section.class.content_type]
scope = scope.scoped :include => :section, :conditions => ["sections.type = ?", section.class.to_s]
scope
end
def update_path
if permalink_changed?
new_path = build_path
unless self.path == new_path
self.path = new_path
@paths_dirty = true
end
end
end
# FIXME this is not hooked up. same in Section. don't we need to call this anyway?
def update_child_paths
if @paths_dirty
self.all_children.each do |child|
child.path = child.build_path
child.save
end
@paths_dirty = false
end
end
def build_path
self_and_ancestors.map(&:permalink).join('/')
end
end