Reputation: 2982
Rails 2.3.5
I have a contact model with 'directory_id' and 'folder_id' foreign keys.
On an index page I have the form to select multiple contacts for the purpose of making a copy of those contacts to a different directory/folder. When the form is submitted, the following params exist (which are all the Contact id's and the Directory and Folder foreign keys):
> "selected_contacts"=>["9", "14", "10", "13", "12", "11"]
> "copy_to_directory"=>"66" (will be directory_id in Contacts)
> "copy_to_folder"=>"59" (will be folder_id in Contacts)
So, I need to find all the contact records, change out the directory_id's and folder_id's and save them as new records (copies).
As far as I know, clone (for a copy with a blank id field) only works on a single record, and save only works on a single record. The only thing I can think of right now would be to loop through each of the "slected_contacts", finding, modifiying and then saving them seperately.
Is there an easy way to do this, or how should I go about doing this?
Thank You!
Upvotes: 0
Views: 1354
Reputation: 876
Loading all selected contacts in one statement could be done like this:
selected_contacts = Contacts.find ["9", "14", "10", "13", "12", "11"]
For cloning those contacts and saving the new copies, I think there is no easier way than implementing a loop.
selected_contacts.each do |contact|
contact_clone = contact.clone
# manipulate contact_clone
contact_clone.save
end
If that's no efficient enough in your case you'll probably have to write custom SQL.
Upvotes: 1