Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails counter cache with condition

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 }
like image 328
Mohammed Sayer Avatar asked Dec 24 '22 05:12

Mohammed Sayer


1 Answers

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?

like image 169
Taha Husain Avatar answered Jan 08 '23 09:01

Taha Husain