开发者

create without using a form in rails

开发者 https://www.devze.com 2023-01-28 10:21 出处:网络
Suppose I have two models A and B Now I want to copy some information from an instance of A to an instance of B by clicking a button

Suppose I have two models A and B

Now I want to copy some information from an instance of A to an instance of B by clicking a button

Is t开发者_如何学Gohere a way of doing it?


This process is called cloning an object and the complexity of it depends on what kind of information you would like to clone.

If you simply want to clone an object's fields, you would do something like this:

old_object = A.find(old_object_id)
new_object = B.new

new_object.field_one = old_object.field_one
new_object.field_two = old_object.field_two
new_object.save!

If, however, you want to also clone the old object's associations, you will need to do that by hand.

Say for the sake of argument that A had a has_many association of B objects called bees, and B has_many C objects called sees, this could get a little complex:

old_object.bees.each do |bee|
   new_bee = bee.clone
   new_bee.sees.each do |see|
      new_see = see.clone
      new_see.save!
   end
   new_object.bees.push(new_bee)
end
new_object.save!
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号