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) a_attributes=@a.attributes 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 2012-12-07 02:30
on 2012-12-07 02:52
On Fri, Dec 7, 2012 at 9:30 AM, renu mehta <lists@ruby-forum.com> 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 > rubyonrails-talk+unsubscribe@googlegroups.com. > For more options, visit https://groups.google.com/groups/opt_out. > > > --
on 2012-12-07 10:13
On 7 December 2012 01:30, renu mehta <lists@ruby-forum.com> 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 2012-12-07 16:25
On Dec 7, 2012, at 4:11 AM, Colin Law 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)
Please log in before posting. Registration is free and takes only a minute.
Existing account
(Switch to SSL-encrypted connection)
NEW: Do you have a Google/GoogleMail or Yahoo account? No registration required!
Log in with Google account | Log in with Yahoo account
Log in with Google account | Log in with Yahoo account
No account? Register here.