Rails has_many association and ActiveRecord#clone
shepherd has_many
animals. I am trying to clone one of them:
dolly=shepherd.animals.bu开发者_开发技巧ild(sheep.clone)
I get error:
undefined method `stringify_keys!' for #<Sheep:0xb6ce154c>
why? what is another way to clone dolly so that she would be associated with a shepherd and have sheep's attributes?
dolly = shepherd.animals.build(sheep.clone.attributes)
build
requires the argument to be a hash of attributes. Otherwise
dolly = shepherd.animals << sheep.clone
ActiveRecord::Base constructors take a parameter hash. Passing an object doesn't quite do it. So you need to query the attributes hash of the object in question.
dolly=shepherd.animals.build(sheep.clone.attributes)
In fact the constructors ignore the id attribute, so you can get away with:
dolly=shepherd.animals.build(sheep.attributes)
精彩评论