2012-05-06 3 views
0

私は、製品のオブジェクトの内部に位置している履歴項目の配列を持っている:オブジェクト内の配列に対する変更をどのように保持するのですか?

class Product 
    include Mongoid::Document 
    include Mongoid::Paranoia 
    include Mongoid::Timestamps 

    ... 
    embeds_many :modification_histories 

マイビズルールは最後の120件の履歴が保存されていることです。新しいものが追加されるときに、私は古いものをソートし、配列ポップ:これは正常に動作しているようだ

if self.modification_histories.size >= 120 
    self.modification_histories.sort! { |x,y| y.date <=> x.date } 
    while self.modification_histories.size >= 120 
    self.modification_histories.pop 
    end 
end 

を、私はそのメソッドの呼び出しや歴史配列の後にブレークポイントを入れているです正しいサイズ。しかし、オブジェクト(self.save!)を保存してリロードすると、ヒストリ配列は変更されません。私は何が間違っているのか分かりません。

gem "mongoid", "~> 2.4"

答えて

0

短い答え:別の配列に配列をコピーします。代わりに:

self.modification_histories.sort! { |x,y| y.date <=> x.date }

arr = self.modification_histories.sort { |x,y| y.date <=> x.date } 
while arr.size >= 120 
    arr.pop 
end 
self.modification_histories = arr 
0

を行うまた、1つの行にそれを圧縮できます。

self.update_attribute(:modification_histories, self.modification_histories.sort{ |x,y| y.date <=> x.date }[0...120]) 
関連する問題