0
votes

so the standard way to use a has_many :through association would be to use the Physician-Appointment-Patient model from the Active Record Association Guide, right? It's basically a more verbose HABTM, with two models having a has_many :through and the connector model having two belongs_to. Now, in my current project I have a model structure like this:

class Cart < ActiveRecord::Base
  has_many :line_items, through: line_item_groups
  has_many :line_item_groups
end

class LineItemGroup < ActiveRecord::Base
  belongs_to :cart
  has_many :line_items
end

class LineItem < ActiveRecord::Base
  belongs_to :line_item_group
  has_one :cart, through: line_item_group
end

Works fine. But now I want a line_item_count on Cart and can't figure out where I should add the counter_cache attribute.

Any help is appreciated :-)

1
I don't think you'll be able to via rails, you'll have to implement it yourself.j-dexx

1 Answers

1
votes

First add line_item_count field in carts table, then in LineItem model add

class LineItem < ActiveRecord::Base
  before_create  :increment_counter
  before_destroy :decrement_counter

  def increment_counter
    Cart.increment_counter(:line_item_count, cart.id)
  end

  def decrement_counter
    Cart.decrement_counter(:line_item_count, cart.id)
  end
end

I didn't tried it, but I think it will solve your problem.