stop following a user if it does not follow any post from this user

63 Views Asked by At

I want to stop following a user if and only if I have left to follow all his posts.

For this I have tried with this method but does not works for me.

user_with_posts = User.find(params[:id])
posts_of_users = user_with_posts.posts
posts_of_users.each do |post|
current_user.unfollow(user_with_posts) unless current_user.follows?(post)
end

The problem here is that if user_with_post have 3 posts and current_user only follow 1 post the code run the current_user.unfollow(user_with_posts)

I want only run the **current_user.unfollow(user_with_posts) if and only if I have left to follow all the post for user_with_posts

1

There are 1 best solutions below

0
On BEST ANSWER

You can use Enumerable#any? for this purpose:

any? [{|obj| block } ] → true or false

Passes each element of the collection to the given block. The method returns true if the block ever returns a value other than false or nil. If the block is not given, Ruby adds an implicit block of {|obj| obj} (that is any? will return true if at least one of the collection members is not false or nil.

user_with_posts = User.find(params[:id])
posts_of_users = user_with_posts.posts
current_user.unfollow(user_with_posts) unless posts_of_users.any? do |post|
  current_user.follows?(post)
end