Store only X most recent entries
I have an model (User) which has a has_many relationship to another model (Resource). There will be a significant number of associated resources g开发者_StackOverflowenerated for a user, but I only wish to store the most recent X records.
Is there a neater way of doing this than:
Load all resources for a given user
If resources == X then delete the first
Add new record.
TIA,
Adam
Use an after_create callback to delete the other entries?
class Resource < ActiveRecord::Base
KEEP_RECORDS = 8
after_create :trim_similar
private
def trim_similar
self.class.where(:user_id => self.user_id).offset(KEEP_RECORDS).each { |r| r.destroy }
end
end
Perhaps not the prettiest destroy method, but it gives you the idea.
精彩评论