0

I have a model called JunkData and a model called Lead. All the fields that JunkData has Lead has as well, including:

first_name
last_name
phone 
address
city
state
zip_code
do_not_mail

Now when the index action of JunkData is invoked, I render all the fields in the index template. However, I have a subtab where all the same data is populated in a form of a new Lead object, and the user is able to change any of the data in the new Lead form.

What is the best way to copy a specific subset of attributes from one model to another that are identical? All I can think of is a loop:

for junk in @junkdata
  lead = Lead.new
  junk.attributes.each_pair do |name, value|
    lead.send(name=, value) if lead.respond_to? name
  end
end
Donato
  • 2,727
  • 6
  • 29
  • 59
  • @BradWerth Yes, it's a duplicate and the answers on that question show a better way to do this. I still think that `id`, `updated_at` and `created_at` shouldn't be copied. It may lead to errors or unexpected behaviour. – Mischa Aug 22 '14 at 07:00
  • @Mischa: Good point. I can't test right now, but I suspect they would be overwritten... This seems relevant, too http://stackoverflow.com/questions/60033/what-is-the-easiest-way-to-duplicate-an-activerecord-record (`dup`) doesn't do those fields, apparently... – Brad Werth Aug 22 '14 at 07:08
  • @BradWerth, I tried it (with SQLite) and `id`, `updated_at` and `created_at` *are not* overwritten. – Mischa Aug 22 '14 at 14:07
  • @Mischa: Wow, that's interesting - good to know! – Brad Werth Aug 22 '14 at 15:49

0 Answers0