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...
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.
delete_all
and destroy_all
with conditionsThese 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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With