Prev | Current Page 271 | Next

Kevin Marshall, Chad Pytel, and Jon Yurek

"Pro Active Record: Databases with Ruby and Rails"


In the following code, you can see the new method that will create more methods
based on the association names, as well as a method that will return a list of associations generated
during the condition block??™s execution:
CHAPTER 5 ?–  BONUS FEATURES 117
module RQuery
class Conditions
def initialize(active_record, &blk)
@active_record = active_record
@columns = []
@associations = {}
define_column_methods
define_association_methods
blk.call(self) unless blk.nil?
end
def define_association_methods
active_record = @active_record
(class << self; self; end).class_eval do
associations = active_record.reflect_on_all_associations
associations.each do |association|
define_method(association.name) do
@associations[association.name] = Conditions.new(association.klass)
end
end
end
end
def to_find_includes
includes = {}
@associations.each do |name, association|
includes[name.to_sym] = association.to_find_includes
end
includes
end
end
end
Our new method for defining the association methods looks an awful lot like the method
for defining the column methods.


Pages:
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283