Module: ActiveObject::Associations::HasManyAssociation::ClassMethods

Defined in:
lib/active_object/associations.rb

Instance Method Summary collapse

Instance Method Details

#has_many(associations, options = {}) ⇒ Object

选项示例: has_many :friends,:class_name=>“User”



171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
# File 'lib/active_object/associations.rb', line 171

def has_many(associations, options = {})

	class_name = options.delete(:class_name) || associations.to_s.singularize.camelize
	write_inheritable_attribute "#{associations}_class",class_name   # 保存关联的类名
	merge_attributes "#{associations}_ids"                            # 将关联ids作为持久化属性

	define_method("#{associations}_ids") do
		self.instance_variable_get("@#{associations}") ? self.instance_variable_get("@#{associations}").object_ids : []
	end

	define_method("#{associations}_ids=") do |value|
		self.instance_variable_set("@#{associations}",Collection.new)
		value.each do |object_id|
			self.instance_variable_get("@#{associations}").append(self.class.read_inheritable_attribute("#{associations}_class").constantize.find(object_id))
		end
	end

	define_method("#{associations}") do
	  self.instance_variable_set("@#{associations}",Collection.new) unless self.instance_variable_get("@#{associations}")
	  self.instance_variable_get("@#{associations}")
	end

end