aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/lib/active_record/base.rb
diff options
context:
space:
mode:
authorDavid Heinemeier Hansson <david@loudthinking.com>2007-12-03 02:01:21 +0000
committerDavid Heinemeier Hansson <david@loudthinking.com>2007-12-03 02:01:21 +0000
commite6f54290aff2982fe1c295d4b0ac6793a55fa112 (patch)
tree06036045473c531ea71e62cf3fae4cedb9fe370a /activerecord/lib/active_record/base.rb
parentc4cb2dd01410417b5ab027aff5d472d68d9cbdb1 (diff)
downloadrails-e6f54290aff2982fe1c295d4b0ac6793a55fa112.tar.gz
rails-e6f54290aff2982fe1c295d4b0ac6793a55fa112.tar.bz2
rails-e6f54290aff2982fe1c295d4b0ac6793a55fa112.zip
Added ActiveRecord::Base#becomes to turn a record into one of another class (mostly relevant for STIs) [DHH]
git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@8259 5ecf4fe2-1ee6-0310-87b1-e25e094e27de
Diffstat (limited to 'activerecord/lib/active_record/base.rb')
-rwxr-xr-xactiverecord/lib/active_record/base.rb14
1 files changed, 14 insertions, 0 deletions
diff --git a/activerecord/lib/active_record/base.rb b/activerecord/lib/active_record/base.rb
index 65dc7275df..c7db48167c 100755
--- a/activerecord/lib/active_record/base.rb
+++ b/activerecord/lib/active_record/base.rb
@@ -1806,6 +1806,20 @@ module ActiveRecord #:nodoc:
record
end
+ # Returns an instance of the specified klass with the attributes of the current record. This is mostly useful in relation to
+ # single-table inheritance structures where you want a subclass to appear as the superclass. This can be used along with record
+ # identification in Action Pack to allow, say, Client < Company to do something like render :partial => @client.becomes(Company)
+ # to render that instance using the companies/company partial instead of clients/client.
+ #
+ # Note: The new instance will share a link to the same attributes as the original class. So any change to the attributes in either
+ # instance will affect the other.
+ def becomes(klass)
+ returning klass.new do |became|
+ became.instance_variable_set("@attributes", @attributes)
+ became.instance_variable_set("@new_record", new_record?)
+ end
+ end
+
# Updates a single attribute and saves the record. This is especially useful for boolean flags on existing records.
# Note: This method is overwritten by the Validation module that'll make sure that updates made with this method
# aren't subjected to validation checks. Hence, attributes can be updated even if the full object isn't valid.