Copying models

Is there an easy way to copy one model to another model with identical
fields? And is there a way to do this associations as well?

For example: If I have a table “items” which has many “tags”, is there
a way to copy from “items” to an identifal table called “temp_items”
without having to manually iterate over each column? And if so, is
there a way to copy the associated “tags” to an identical table called
“temp_tags”? Thanks in advance.

Scott

On 11/12/06, Scott [email protected] wrote:

Scott


Posted via http://www.ruby-forum.com/.

Scott,

AR overrides clone() to handle shallow copies. As for associations
you’ll have to handle these yourself. Here is a cut-and-paste from
the rails source so you can see the implementation.

module ActiveRecord
class Base

  # Returns a clone of the record that hasn't been assigned an id 

yet and
# is treated as a new record. Note that this is a “shallow”
clone:
# it copies the object’s attributes only, not its associations.
# The extent of a “deep” clone is application-specific and is
therefore
# left to the application to implement according to its need.
def clone
attrs = self.attributes_before_type_cast
attrs.delete(self.class.primary_key)
self.class.new do |record|
record.send :instance_variable_set, ‘@attributes’, attrs
end
end

end
end

Hope this helps.


Zack C.
http://depixelate.com

Zack, it turns out that what I was looking for was attributes() but your
suggestion led me to that, thanks. The problem with clone is it creates
a copy of the same data type and doesn’t allow me to assign it to a
different data type with identical attributes. So attributes() creates
a hash of the object which then allows me to create the temp data type
using that hash.

Scott

Zack C. wrote:

On 11/12/06, Scott [email protected] wrote:

Scott


Posted via http://www.ruby-forum.com/.

Scott,

AR overrides clone() to handle shallow copies. As for associations
you’ll have to handle these yourself. Here is a cut-and-paste from
the rails source so you can see the implementation.

module ActiveRecord
class Base

  # Returns a clone of the record that hasn't been assigned an id 

yet and
# is treated as a new record. Note that this is a “shallow”
clone:
# it copies the object’s attributes only, not its associations.
# The extent of a “deep” clone is application-specific and is
therefore
# left to the application to implement according to its need.
def clone
attrs = self.attributes_before_type_cast
attrs.delete(self.class.primary_key)
self.class.new do |record|
record.send :instance_variable_set, ‘@attributes’, attrs
end
end

end
end

Hope this helps.


Zack C.
http://depixelate.com