Ruby 如何克隆具有多个关联的 类栏
您可以编写Ruby 如何克隆具有多个关联的 类栏,ruby,clone,Ruby,Clone,您可以编写Bar.new(Bar.attributes.reject\u at(“id”,“foo\u id”)) 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.colle
Bar.new(Bar.attributes.reject\u at(“id”,“foo\u id”))
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 }
foo.bars << oldFoo.bars.all.collect { |bar| Bar.new(bar.attributes) }
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