Ruby on Rails:如何将对象从一个类别复制到另一个类别

时间:2017-04-21 14:23:32

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.2

我正在尝试将一些最新的收件人(订阅者)复制到我的简报应用中的新类别。我在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错误。

1 个答案:

答案 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
}