Rails counter cache with condition

大憨熊 提交于 2019-12-24 00:54:44

问题


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 }

回答1:


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?



来源:https://stackoverflow.com/questions/51642621/rails-counter-cache-with-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!