【问题标题】:remove a record from has_many without deleting from db? (rails 2.3.5)从 has_many 中删除记录而不从数据库中删除? (轨道 2.3.5)
【发布时间】:2012-02-17 12:59:28
【问题描述】:

在处理has_many 时,看起来delete 和destroy 都从数据库中删除了记录。无论如何不要这样做。换句话说,我想在将 has_mnay 集合传递给方法之前对其进行修剪,但我不希望我的更改保留到数据库。在控制台上尝试它,当我这样做时它似乎立即删除

second_acct = users.accounts[1]
users.accounts.delete(second_acct)

我的用例类似于我只想将支票帐户传递给一个方法,因此我想从用户中删除这些帐户。

【问题讨论】:

  • 为了确保我在这里清楚,我不想碰数据库,我只想删除内存中的关系
  • 你有没有找到办法做到这一点?

标签: ruby-on-rails


【解决方案1】:
second_acct = users.accounts[1]
second_acct.update_attribute(:user_id, nil)

这应该可行。

或者这个:

second_acct.user = nil
second_acct.save

【讨论】:

    【解决方案2】:

    您的协会是如何成立的?

    collection.delete(object, …)
        Removes one or more objects from the collection by setting their foreign keys to NULL. Objects will be in addition destroyed if they’re associated with :dependent => :destroy, and deleted if they’re associated with :dependent => :delete_all.
    

    因此,如果您不想删除记录而只清除关联,请移除 :dependent => :destroy:dependent => :delete_all 选项。

    【讨论】:

    • 我有依赖 => :destroy,当我真正删除它们时,我希望它们从数据库中清除。在上面的情况下,我不想碰数据库,只需将它们从内存中的集合中删除..
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-06
    • 1970-01-01
    相关资源
    最近更新 更多