开发者

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:

  1. Load all resources for a given user

  2. If resources == X then delete the first

  3. 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜