Class: Og::HasMany

Inherits:
Relation show all
Defined in:
lib/og/relation/has_many.rb

Overview

A ‘has_many’ relation. There should be a respective ‘belongs_to’ relation.

Examples

article.comments << Comment.new article.comments.size

Instance Attribute Summary

Attributes inherited from Relation

#options

Instance Method Summary collapse

Methods inherited from Relation

#[], #[]=, enchant, #initialize, #method_missing, #resolve_options, #resolve_target

Constructor Details

This class inherits a constructor from Og::Relation

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class Og::Relation

Instance Method Details

#enchantObject



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
# File 'lib/og/relation/has_many.rb', line 23

def enchant
	self[:owner_singular_name] = owner_class.to_s.demodulize.underscore.downcase 
	self[:target_singular_name] = target_plural_name.to_s.singular
	self[:foreign_key] = "#{foreign_name || owner_singular_name}_#{owner_pk}"
	
	owner_class.module_eval %{ 
		attr_accessor :#{target_plural_name}

		def #{target_plural_name}(options = nil)
			unless @#{target_plural_name}
				@#{target_plural_name} = HasManyCollection.new(
					self, 
					:add_#{target_singular_name},
					:remove_#{target_singular_name},
					:find_#{target_plural_name},
					options
				)
			end

			@#{target_plural_name}.reload(options) if options and options[:reload]
			@#{target_plural_name}
		end

		def add_#{target_singular_name}(obj)
			obj.#{foreign_key} = @#{owner_pk}
			obj.save
		end

		def remove_#{target_singular_name}(obj)
			obj.#{foreign_key} = nil
		end
		
		def find_#{target_plural_name}(options = {})
			find_options = {
				:condition => "#{foreign_key} = \#\{@#{owner_pk}\}"
			}
			find_options.update(options) if options
			#{"find_options.update(:order => #{options[:order].inspect})" if options[:order]}
			#{target_class}.find(find_options)
		end
	}
end