![](/img/trans.png)
[英]How to create unlimited objects from one submit event in 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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.