Ruby on Rails: 如何将对象从一个类别复制到另一个类别
Ruby on Rails: how to copy objects from one category to another
我正在尝试将一些最新的收件人(订户)复制到我的时事通讯应用程序中的新类别。我 运行 遵循 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
错误。
这可能不是最干净的方法,但应该可行:)
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
}
我正在尝试将一些最新的收件人(订户)复制到我的时事通讯应用程序中的新类别。我 运行 遵循 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
错误。
这可能不是最干净的方法,但应该可行:)
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
}