0

This seems fairly straightforward.

@new_email.distributions = @email.distributions.dup

After this is performed, both share identical distributions.

However, once the new object "saves". The old one loses all of its distributions.

Why is that?

FYI:

Distributions belongs_to :email. Email has_many :distributions

Trip
  • 26,756
  • 46
  • 158
  • 277

3 Answers3

2

The way you model this causes the problem!

Each Distribution can only belong to just one email ... that email_id attribute is already set, and a Distribution can not belong to two emails! (there is only one email_id attribute in a Distribution).

You should use a "many-to-many" or "has-many-through" relation to model the association between your two models, and a join table between them, so you can store how distributions belong to more than just one email.

Tilo
  • 33,354
  • 5
  • 79
  • 106
1

Try using cloneinstead of dup.

davidb
  • 8,884
  • 4
  • 36
  • 72
0

Because you using same object, try: some_other_var = @email.distributions.dup if I understood you correctly

  • It's a different object. `@email = Email.find(params[:id]) @new_email = @email.clone @new_email.distributions = @email.distributions.dup` – Trip Oct 26 '11 at 18:19