Search code examples
ruby-on-railsarraysduplication

How can I duplicate an array to another object?


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


Solution

  • 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.