从had_many中删除记录而不从db中删除? (栏杆2.3.5)

时间:2012-02-17 12:59:28

标签: ruby-on-rails

它看起来像删除&在处理has_many时,destroy会从db中删除记录。无论如何不要这样做。换句话说,我想在将一个has_mnay集合传递给方法之前修剪它,但我不希望我的更改持久存储到数据库中。在控制台上尝试它时,它似乎立即删除

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

我的用例就像是我想只将支票帐户传递给方法,所以我想从用户那里删除这些帐户。

2 个答案:

答案 0 :(得分:0)

second_acct = users.accounts[1]
second_acct.update_attribute(:user_id, nil)

这应该有用。

或者这个:

second_acct.user = nil
second_acct.save

答案 1 :(得分:-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选项。