2012-06-25 41 views
0
class Bar < ActiveRecord::Base 
    belongs_to :foo 
end 

class Foo < ActiveRecord::Base 
    has_many :bars 
end 

Foo oldFoo = Foo.new 

Foo foo = Foo.new 
foo.bars << oldFoo.bars.all.collect { |bar| bar.clone } 

上述命令不會正確替換bars.foo_id,oldFoo.bars的引用將被刪除並設置爲foo.bars。如何克隆has_many關聯

我該如何正確地做到這一點?

回答

0
foo.bars << oldFoo.bars.all.collect { |bar| Bar.new(bar.attributes) } 

受保護的屬性分配將在R3.2中引發錯誤。

UPDATE:

看起來像它一樣的東西clone,所以它不是要好得多。如果你定義的方法(我使用它們很多):

class Hash 
def select_at(*s_keys) 
    Hash[s_keys.zip(values_at(*s_keys))] 
    end 

    def reject_at(*r_keys) 
    select_at(keys - r_keys) 
    end 
end 

你可以寫Bar.new(bar.attributes.reject_at("id", "foo_id"))