如何删除内置资源?

问题描述 投票:3回答:3
class Post < ActiveRecord::Base
  belongs_to :user
end

class User < ActiveRecord::Base
  has_many :posts
end

我的问题是如何通过迭代删除构建的资源?让我们说我有许多BUILT用户(尚未在数据库中)帖子。如何删除特定帖子?我尝试了这种方法,但是没有:

@user.posts.each {|post| post.delete if post.content.nil? }

当然它通过帖子,执行'删除'方法,但所有的帖子都是他们在开始的地方...

ruby-on-rails ruby
3个回答
2
投票

由于您正在使用未提交到数据库的built对象,因此destroy对象上的常规方法deletePost将无法工作。您将不得不直接处理@user.posts系列。

我通常使用这种方法:

@user.posts.each { |post| @user.posts.destroy(post) if post.content.nil? }

它从rails控制台运行良好。

About delete_all and destroy_all with conditions

这两种方法会派上用场,但它们是ActiveRecord::Relation域的一部分。 @user.posts集合是一个关联而不是关系,所以它只暴露delete_all方法,没有条件。

如果你想使用它们,你应该尝试这样的事情:

 Post.delete_all(user_id: @user, content: nil)

2
投票

使用delete_all标准

@user.posts.delete_all("content IS NULL")

See here了解更多信息。


0
投票

你可以使用reset方法。它卸载了关联。 Method API here

这将删除所有未提交到数据库的built对象:

@user.posts.reset
© www.soinside.com 2019 - 2024. All rights reserved.