I have the following (this has been simplified to make the question at
hand more obvious):
user model has_many favorites
favorite model belongs_to user
After a new user is created, I want to copy all the favorites from an
existing user to the new user. Right now I have the following code:
# bob is the existing user and sam is the new user
bob.favorites.each do | f |
u = Favorite.new(f.attributes)
u.user_id = sam.user_id
This creates an SQL INSERT for every favorite that bob has.
I know SQL could do this in one command with something like:
INSERT INTO favorites SELECT url, sam.user_id AS user_id FROM
favorites WHERE user_id = bob.user_id
Does ActiveRecord have something in place for me to do this? I would
be nice to keep the code in Ruby rather than SQL.
Thanks in advance.