Reputation: 17981
If I have record A which has been saved in the database, then I want to replace it with a newly created record B which has not been saved. So B can then be saved in the database but with the id of from A (and A is replaced). Is this possible in Rails Active Record?
P.S. the reason behind this is that I need to merge objects by some condition, and constructing an object requires some internet fetching/parsing. So if time is used to parse B I want to prevent parsing it again for A, but replacing it with B.
Upvotes: 1
Views: 1384
Reputation: 43298
You can do something like this:
a = A.find(1)
b = B.new
# Modify b
a.update_attributes(b.attributes.delete_if{ |k,v| %w(id created_at updated_at).include?(k) })
Upvotes: 2
Reputation: 11967
Try something like this(didn't test this code):
a = Model.find(params[:id])
b = Model.new(params)
a.update_attributes(b.attributes)
Upvotes: 2