counter_cache with has_many :through

前端 未结 3 1196
温柔的废话
温柔的废话 2020-11-30 04:59

I just created a counter_cache field and the controller looks like this.

 @users = User.where(:sex => 2).order(\'received_likes_count\')
<
3条回答
  •  萌比男神i
    2020-11-30 05:22

    According to this post (from last month) and this post (from 2008), it doesn't seem to be possible. However, the latter post does have code for a workaround (copy/paste'd from that link for your convenience, credit goes to DEfusion in the second link)

    class C < ActiveRecord::Base
        belongs_to :B
    
        after_create :increment_A_counter_cache
        after_destroy :decrement_A_counter_cache
    
        private
    
        def increment_A_counter_cache
            A.increment_counter( 'c_count', self.B.A.id )
        end
    
        def decrement_A_counter_cache
            A.decrement_counter( 'c_count', self.B.A.id )
        end
    end
    

    (This is for a scheme where C belongs_to B, B belongs_to A, A has_many C :through => B

提交回复
热议问题