Skip to content
This repository has been archived by the owner on May 21, 2024. It is now read-only.

Commit

Permalink
Add a few explanations to AR::View.
Browse files Browse the repository at this point in the history
  • Loading branch information
mschuerig committed Apr 8, 2009
1 parent 3db917d commit e313215
Showing 1 changed file with 23 additions and 7 deletions.
30 changes: 23 additions & 7 deletions lib/active_record/view.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@

module ActiveRecord
# A base class for database views.
# It is primarily useful for views that are centered around a single table/model
module ActiveRecord # :nodoc:
class View < Base
self.abstract_class = true

Expand All @@ -8,6 +10,12 @@ def readonly?
end

class << self
# Clones all applicable associations from +model+ to this view
# and provides an instance method
# <tt>to_<em>model</em></tt>
# that casts a view object to an object of the kind view is
# based on. This latter object may be missing attributes; to fill
# them in, call #reload.
def based_on(model)
define_method("to_#{model.name.demodulize.underscore}") do
becomes(model)
Expand All @@ -18,6 +26,11 @@ def based_on(model)
end
end

# Clone one or more associations from +model+ to this view class.
#
# NOTE: Currently only <tt>belongs_to</tt>, <tt>has_many</tt> (withouth
# <tt>:through</tt>), and <tt>has_and_belongs_to_many</tt> associations
# are supported.
def clone_association(model, *associations)
associations.each do |association|
r = case association
Expand All @@ -30,13 +43,14 @@ def clone_association(model, *associations)
end
case r.macro
when :belongs_to
### TODO handle polymorphic associations
if self.column_names.include?(r.primary_key_name.to_s)
options = r.options.merge(
:class_name => r.class_name,
:foreign_key => r.primary_key_name
)
belongs_to r.name, options
if !r.options[:foreign_type] || self.column_names.include?(r.options[:foreign_type])
options = r.options.merge(
:class_name => r.class_name,
:foreign_key => r.primary_key_name
)
belongs_to r.name, options
end
end
when :has_many
### TODO :through assocications
Expand All @@ -52,6 +66,8 @@ def clone_association(model, *associations)
:association_foreign_key => r.association_foreign_key
)
has_and_belongs_to_many r.name, options
when :has_one
### TODO
end
end
end
Expand Down

0 comments on commit e313215

Please sign in to comment.