Copy common attributes

Hello,

If I have a model A as :

name
address
phone

and model B as:

name
address
email

Is it possible to copy a record from A to B with one statement? I am
trying :

@a=A.find(2)
[email protected]
a_attributes.delete “id”
@b=B.create(a_attributes)

@b.save!

And I am getting an exception :

unknown attribute: phone

How can do this without going through each attribute individually?

Thanks.

On Fri, Dec 7, 2012 at 9:30 AM, renu mehta [email protected] wrote:

name

@b.save!

And I am getting an exception :

unknown attribute: phone

How can do this without going through each attribute individually?

use slice.

B.create a.attributes.slice(:name, :address, :email)

To unsubscribe from this group, send email to
[email protected].
For more options, visit https://groups.google.com/groups/opt_out.

On 7 December 2012 01:30, renu mehta [email protected] wrote:

name
address
email

My first suggestion would be that maybe the database design could be
improved. If there are tables with common fields then possibly the
common data should be moved to a separate table, or perhaps even the
two original tables should be merged. It is a nightmare trying to
keep tables with common data in sync.

Colin

On Dec 7, 2012, at 4:11 AM, Colin L. wrote:

Colin
I agree with Colin. However, if you have a specific need (such as data
conversion), then you can do something like:

irb1.9.3> JudgedEvent.column_names
#1.9.3 => [“id”, “number”, “name”, “created_at”, “updated_at”, “year”,
“event_description_id”]
irb1.9.3> EventDescription.column_names
#1.9.3 => [“id”, “name”, “name_for_certificate”, “description”,
“created_at”, “updated_at”]
irb1.9.3> cols = EventDescription.column_names - %w[ id created_at
updated_at ]
#1.9.3 => [“name”, “name_for_certificate”, “description”]
irb1.9.3> JudgedEvent.first.attributes.slice(cols)
JudgedEvent Load (0.8ms) SELECT “judged_events”.
FROM
“judged_events” LIMIT 1
#1.9.3 => {“name”=>“Financial Analyst Team”}

Note that there are columns in EventDescription (like ‘email’ in your
‘B’ above) that are not present in JudgedEvent (your ‘A’), but slice’ing
them doesn’t affect the attributes hash that will be passed on to the
.new method. The “extra” columns in the destination that are missing
from the source are effectively ignored, but if the source ever expands
to include any of them, then they will be automagically* included.

-Rob

*(no actual magic involved)