Moving a record

2 views
Skip to first unread message

wiz...@gmail.com

unread,
Aug 13, 2007, 2:19:14 PM8/13/07
to Ruby on Rails: Talk
Hi!

I'd like to move a record from one table to another. I've been
reading the documentation, and I think I can accomplish this by
finding the record, creating a new record with those attributes, and
then removing the first one. First, is there a better way to do this?

Next question, if I do go this way, do I have to specify every column
that is going to be inserted into the database? For example, I would
have to do this....

.new(:col1 => blah, :col2 => blah, :col3 => blah).save

or can I just use the results from the previous find and insert them
into the .new() part? I tried to put the @results in
(.new(@results).save), but that obviously didn't work.


Thanks!

Matthew Isleb

unread,
Aug 13, 2007, 3:09:45 PM8/13/07
to rubyonra...@googlegroups.com
You could do it in one line:

NewModel.create(OldModel.find(id).destroy.attributes)

That provides no error checking or exception handling, of course. But
I'm a sucker for oneliners. :-)

Since it is destroying the old record before creating the new one, you
may want to wrap it in a transaction. Or just expand it to more lines
and ensure that the new record is created before destroying the old.
However you prefer. The key is to use the attributes Hash.

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

wiz...@gmail.com

unread,
Aug 13, 2007, 5:17:03 PM8/13/07
to Ruby on Rails: Talk
Ah, thank you very much... a little tweaking of the code and it
worked.


MainArchive.create(Response.find(params[:id]).destroy.attributes).save

thanks for your help!!!!

mike


On Aug 13, 2:09 pm, Matthew Isleb <rails-mailing-l...@andreas-s.net>
wrote:

Matthew Isleb

unread,
Aug 13, 2007, 5:27:02 PM8/13/07
to rubyonra...@googlegroups.com
wiz...@gmail.com wrote:

>
> MainArchive.create(Response.find(params[:id]).destroy.attributes).save

You shouldn't have to do that final save. create() saves for you.

Reply all
Reply to author
Forward
0 new messages