ruby-on-rails - Mongoid::Paranoia 删除关联

标签 ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-3.2 mongoid

user.rb模型

class User
  include Mongoid::Document
  include Mongoid::Paranoia
  has_many :posts, dependent: :destroy, :autosave => true
end

post.rb模型

class Post
  include Mongoid::Document
  belongs_to :user
  field :title
end

如果我在控制台中运行下一个命令:

irb(main):020:0> u = User.first
=> #object here
irb(main):021:0> u.delete
=> true
irb(main):022:0> u.posts
=> nil

如果我尝试调用用户帖子,我可以看到所有用户帖子 已被删除。如果使用 u.destroy 将用户从我的数据库中永久销毁,我希望删除所有用户帖子。

如果我使用 Mongoid::Paranoia 删除一个对象,我如何在我的数据库中保留所有相关对象 u.delete for this object can be restore稍后使用 u.restore

谢谢!

最佳答案

您可以覆盖 remove method在由 Mongoid::Paranoia 提供的 User 中,因此它省略了 cascade! 调用:

  def remove(options = {})
    # don't cascade the remove call
    # cascade!
    time = self.deleted_at = Time.now
    paranoid_collection.find(atomic_selector).
      update({ "$set" => { paranoid_field => time }})
    @destroyed = true
    IdentityMap.remove(self)
    Threaded.clear_options!
    true
  end
  alias :delete :remove

现在 u.delete 将完整保留所有关联的帖子,u.delete! 也将永久删除它们。

关于ruby-on-rails - Mongoid::Paranoia 删除关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15637940/

相关文章:

ruby-on-rails - 返回值的 RSpec 序列和从 stub 中引发的错误

mysql - 在 Rails 上的架构中设置全局变量

Ruby 将数组的内容输出为逗号分隔的字符串 Ruby

ruby-on-rails - 使用 Devise Gem 自定义密码保存

mysql - ruby:使用mysql/mysqlplus时如何指定编码?

javascript - 如何以编程方式处理英文缩写 [Regex, JS, Ruby]

ruby-on-rails - Rails 3 长文本迁移

ruby-on-rails - 使用 Rack::Attack 防止快速登录尝试

javascript - 拖动 map 更改搜索结果

ruby-on-rails - Rails fixtures 和命名空间模型 - ActiveRecord::Fixture::FixtureError