我正在尝试将一些最新的收件人(订阅者)复制到我的简报应用中的新类别。我在Rails控制台中运行了以下代码行,但不是将收件人复制到新类别,而是将最新的10个收件人移动到新类别。看起来recipient.clone
无效。我正在使用Ruby v2.0.0
和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
}
更新
我试过
recipients.each{ |recipient|
recipient.freeze
@recipient_clone = recipient.dup
@recipient_clone = @recipient_clone.category_id=63
@recipient_clone.save
}
但它会导致NoMethodError: private method 'initialize_dup' called
错误。
答案 0 :(得分:0)
它可能不是最干净的方式,但应该有效:)
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
}