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? }
当然它通过帖子,执行'删除'方法,但所有的帖子都是他们在开始的地方...
由于您正在使用未提交到数据库的built
对象,因此destroy
对象上的常规方法delete
,Post
将无法工作。您将不得不直接处理@user.posts
系列。
我通常使用这种方法:
@user.posts.each { |post| @user.posts.destroy(post) if post.content.nil? }
它从rails控制台运行良好。
delete_all
and destroy_all
with conditions这两种方法会派上用场,但它们是ActiveRecord::Relation
域的一部分。 @user.posts
集合是一个关联而不是关系,所以它只暴露delete_all
方法,没有条件。
如果你想使用它们,你应该尝试这样的事情:
Post.delete_all(user_id: @user, content: nil)