Search code examples
ruby-on-rails-3android-activitymodelsti

Rails 3 destroy oldest item in database if user owns more than 10


I have an Activity stream I have designed using STI in rails 3.

I want to do a check to see if a user has more than 10 activity items on create. When a user creates his 11th Activity in the database, I want it to destroy the oldest record * essentially the first record the user made and so on.* This way I am keeping my database clean of thousands of old useless records.

I am assuming I would start at the model level, but since I dont want to define the "current_user" in the model, it should be in the controller.

Any help would be appreciated to accomplish this task, I am fairly new at these type of more advanced tasks in rails.


Solution

  • You can hook this logic up in an AR callback. Assuming you kept rails conventions when modeling you classes, and each activity belongs to a user, you can then easily do the following in your Activity model:

    after_save do |record|
      if Activity.where(:user => record.user).count >= 11
        Activity.where(:user => record.user).order('created_at asc').first.destroy
      end
    end
    

    I guess this will create three transactions to the db (one for count, another to find the first record, and one to delete it). I wonder if there's a more efficient way to do this, as it will be invoked on every Activity#save...