如何将数组复制到另一个对象?

发布于 2024-12-12 15:54:55 字数 284 浏览 3 评论 0原文

这看起来相当简单。

@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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

人间不值得 2024-12-19 15:54:57

因为您使用相同的对象,请尝试: some_other_var = @email.distributions.dup 如果我理解正确的话

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

漫雪独思 2024-12-19 15:54:56

您的建模方式会导致问题!

每个分发只能属于一封电子邮件...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 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.

猫瑾少女 2024-12-19 15:54:56

尝试使用clone而不是dup

Try using cloneinstead of dup.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文