0

I'm trying to copy some latest recipients (subscribers) to a new category in my newsletter app. I ran following lines of code in Rails console but instead of copying recipients to new category it moved latest 10 recipients to new category. It looks like recipient.clone is not working. I'm using Ruby v2.0.0 and Rails v3.2.11.

recipients = Recipient.where(category_id: 54).order('created_at DESC').take(10)
recipients.each{ |recipient| 
  @recipient_clone = recipient.clone
  @recipient_clone.category_id=63
  @recipient_clone.save
}

UPDATE:

I tried

recipients.each{ |recipient| 
  recipient.freeze
  @recipient_clone = recipient.dup
  @recipient_clone = @recipient_clone.category_id=63
  @recipient_clone.save
}

but it gives NoMethodError: private method 'initialize_dup' called error.

rkb
  • 514
  • 2
  • 9
  • 19

1 Answers1

0

It might not be the cleanest way, but it should work :)

recipients = Recipient.where(category_id: 54).order('created_at DESC').take(10)
recipients.each{ |recipient| 
  @recipient_clone = Recipient.new(recipient.attributes.except(:id))
  @recipient_clone.category_id=63
  @recipient_clone.save
}
Samir Haddad
  • 159
  • 2
  • 10
  • Yay, this should work. We used a similar approach `Recipient.new(:email => r.email, :first_name => r.first_name ....)` as we had to exclude many attributes and it worked. – rkb Apr 22 '17 at 07:20
  • I'm waiting if we can get a better explanation why `recipient.dup` did not work otherwise I'll accept your answer. – rkb Apr 22 '17 at 07:28
  • You said you are using Rails v3.2.11, right? This issue says you should use Rails 3.2.13 or greater. https://github.com/airblade/paper_trail/issues/294 – Samir Haddad Apr 22 '17 at 14:33