How can I cache a calculated column in rails?

前端 未结 5 1042
感动是毒
感动是毒 2020-12-14 03:06

I have a tree of active record objects, something like:

class Part < ActiveRecord::Base
  has_many :sub_parts, :class_name => \"Part\"

  def complicat         


        
5条回答
  •  孤城傲影
    2020-12-14 03:56

    I suggest using association callbacks.

    class Part < ActiveRecord::Base
      has_many :sub_parts,
        :class_name => "Part",
        :after_add => :count_sub_parts,
        :after_remove => :count_sub_parts
    
      private
    
      def count_sub_parts
        update_attribute(:sub_part_count, calculate_sub_part_count)
      end
    
      def calculate_sub_part_count
        # perform the actual calculation here
      end
    end
    

    Nice and easy =)

提交回复
热议问题