The best way to delete a collection on a specified condition
19 views
Skip to first unread message
Serguei Cambour
unread,
Aug 6, 2016, 1:10:01 PM8/6/16
Reply to author
Sign in to reply to author
Forward
Sign in to forward
Delete
You do not have permission to delete messages in this group
Copy link
Report message
Show original message
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
to Ruby on Rails: Talk
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 ?
You do not have permission to delete messages in this group
Copy link
Report message
Show original message
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
to Ruby on Rails: Talk
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.
You do not have permission to delete messages in this group
Copy link
Report message
Show original message
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
to Ruby on Rails: Talk
Thank you Colin.
Yes, I know about callbacks, I don't care about it in this case. I just want to clean posts and keep not more than the last 25 ones. Thank you for the tip regarding the ordering, I'll take care about that.
Serguei Cambour
unread,
Aug 7, 2016, 5:59:05 AM8/7/16
Reply to author
Sign in to reply to author
Forward
Sign in to forward
Delete
You do not have permission to delete messages in this group
Copy link
Report message
Show original message
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
to Ruby on Rails: Talk
Just one editing, - I had to use a plural form with includes as follows:
users = includes(:posts)
to have eager loading of posts association for every User.
On Saturday, 6 August 2016 19:10:01 UTC+2, Serguei Cambour wrote: