【问题标题】:Rails has_many association and ActiveRecord#cloneRails has_many 关联和 ActiveRecord#clone
【发布时间】:2009-11-27 15:37:28
【问题描述】:
牧羊人has_many 动物。我正在尝试克隆其中一个:
dolly=shepherd.animals.build(sheep.clone)
我得到错误:
undefined method `stringify_keys!' for #<Sheep:0xb6ce154c>
为什么?还有什么方法可以克隆多莉,让她与牧羊人相关联并具有绵羊的属性?
【问题讨论】:
标签:
ruby-on-rails
ruby
activerecord
has-many
【解决方案1】:
dolly = shepherd.animals.build(sheep.clone.attributes)
build 要求参数是属性的散列。否则
dolly = shepherd.animals << sheep.clone
【解决方案2】:
ActiveRecord::Base 构造函数采用参数散列。传递一个对象并不能完全做到这一点。因此,您需要查询相关对象的属性哈希。
dolly=shepherd.animals.build(sheep.clone.attributes)
实际上构造函数忽略了 id 属性,所以你可以侥幸逃脱:
dolly=shepherd.animals.build(sheep.attributes)