如何将数组复制到另一个对象?
这看起来相当简单。
@new_email.distributions = @email.distributions.dup
执行此操作后,两者共享相同的分布。
然而,一旦新对象“保存”。旧的失去了所有的发行版。
这是为什么?
仅供参考:
分发belongs_to :email
。电子邮件 has_many :distributions
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
因为您使用相同的对象,请尝试:
some_other_var = @email.distributions.dup
如果我理解正确的话Because you using same object, try:
some_other_var = @email.distributions.dup
if I understood you correctly您的建模方式会导致问题!
每个分发只能属于一封电子邮件...
email_id
属性已设置,并且一个分发不能属于两个电子邮件电子邮件! (分发中只有一个email_id
属性)。您应该使用“多对多”或“有多通”关系对两个模型之间的关联进行建模,并使用它们之间的连接表,以便您可以存储分布的归属方式不止一封电子邮件。
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 oneemail_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.
尝试使用
clone
而不是dup
。Try using
clone
instead ofdup
.