Rails counter cache with condition
Asked Answered
L

1

6

I have a rails hotel application which has rooms inside it. Rooms can have n number of tickets associated to them. I have create a counter cache with counter culture gem which updates the room table with number of tickets assigned to it, the problem is i only want count of tickets which are open or in progress state. I have this code it works fine normally but does not work with the condition can anyone guide me by letting me know how can i work it with conditions? Any help is appreciated

Room Table Migration file

 class AddTicketsCountToRooms < ActiveRecord::Migration[5.0]
    def self.up
      add_column :rooms, :tickets_count, :integer, null: false, default: 0
    end
  end

Ticket.rb file

    belongs_to :room
  counter_culture :room, column_name: proc {|model| model.status? [0,1] 'tickets_count' : nil }

This does not go according to the where clause and gives me error saying

syntax error, unexpected tSTRING_BEG, expecting '}' {|model| model.status? [0,1] 'tickets_count' : nil } ^ /Users/mohammedsayerwala/Documents/Aqua/app/models/ticket.rb:8: syntax error, unexpected ':', expecting keyword_end tatus? [0,1] 'tickets_count' : nil }
Lemos answered 1/8, 2018 at 21:39 Comment(0)
A
11

Rails does not provide conditions with counter_cache. where clause and each is not going to work either.

To achieve conditional counter, you can use custom callbacks in your code to manage counter blog on custom counter_cache with conditions.

Alternatively, you can use counter_culture gem, conditional-counter-cache

please refer answers on similar question - Counter Cache for a column with conditions?

Arvind answered 2/8, 2018 at 9:11 Comment(2)
i worked with the counter_culture gem but the conditions isnt working i followed the step in the link and have something as counter_culture :room, column_name: proc {|model| model.status? [0,1] 'tickets_count' : nil } but it gives me an error saying syntax error, unexpected tIDENTIFIER, expecting keyword_do or '{' or '(' :room, column_name: proc {|model| model.status? [0,1 @tahahussain, i have even edited my question accordinglyLemos
@MohammedSayer looks like there's a syntax error in ternary condition you are using in proc. Please modify your proc as counter_culture :room, column_name: proc {|model| model.status.in?([0,1]) ? 'tickets_count' : nil }Arvind

© 2022 - 2024 — McMap. All rights reserved.