On 6 August 2016 at 08:51, Serguei Cambour <s.cambour@gmail.com> wrote:
> I wonder what is the best way to delete all the records of the association
> on a specified condition.
> For example, you have User model that has many Post(s). How would keep all
> the recent User's Posts and delete all the last Posts when a Users have more
> than 25 ?
>
> There is a solution like that:
>
> def self.delete_old_posts
> old_posts = []
> users = includes(:post)
> users.each do |user|
> old_posts =+ user.posts.offset(25) unless user.posts.empty?
> end
>
>
> old_posts.delete_all
> end
>
> Any other ideas ? Thank you.
You need to order the posts otherwise there is no guarantee which ones
will be deleted. I don't think you need includes(:post). Also you
don't need the unless. Are you sure you want delete_all? That will
not call callbacks. In fact I am not sure you can use delete_all in
this situation.
Colin
>
> --
> You received this message because you are subscribed to the Google Groups
> "Ruby on Rails: Talk" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to rubyonrails-talk+unsubscribe@googlegroups.com.
> To post to this group, send email to rubyonrails-talk@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/rubyonrails-talk/e72d40de-1f2b-494c-8e47-ff172c4cd817%40googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.
--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-talk+unsubscribe@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/CAL%3D0gLujwZNO1RH68ketACmA1GOOgNputuAE7jjPhGuNLrq6MA%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.
No comments:
Post a Comment