Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete built resource?

class Post < ActiveRecord::Base
  belongs_to :user
end

class User < ActiveRecord::Base
  has_many :posts
end

My question is how to delete built resource with iteration? Lets say i have user with many BUILT (not yet in the database) posts. How can i delete specific posts? I tried this aproach but nope:

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

Of course it goes through posts, execute 'delete' method, but all the posts are where they were at the beginning...

like image 557
Leo Avatar asked Sep 15 '25 07:09

Leo


1 Answers

Since you are working with built objects that are not been committed to the database, the regular methods destroy, delete on the Post objects will not work. You will have to deal with the @user.posts collection directly.

I usually use this approach:

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

It's working fine from the rails console.

About delete_all and destroy_all with conditions

These two methods would come in handy, but they are part of the ActiveRecord::Relation domain. The @user.posts collection is an association and not a relation, so it only exposes the delete_all method with no conditions.

If you want to use them, you should try something like this:

 Post.delete_all(user_id: @user, content: nil)
like image 53
marzapower Avatar answered Sep 17 '25 23:09

marzapower