I migrated this to enable counter cache
class AddUniquecodesCountToUser < ActiveRecord::Migration
def up
add_column :users, :uniquecodes_count, :integer, :default => 0
User.reset_column_information
User.all.each do |p|
User.reset_counters(p.id, :uniquecodes)
end
end
def down
remove_column :users, :uniquecodes_count
end
end
I'm usually fetching the number of uniquecodes the user has by this code
current_user.uniquecodes.joins(:community).merge(Community.not_deleted).order("uniquecodes.updated_at DESC").count.to_s
models/community.rb
....
def self.not_deleted
where deleted_at: nil
end
....
The reason why I'm doing this is, there is possibility that community record could be deleted. So that I don't want to display uniquecodes once related community has deleted.
As you see my migration file, it just counts up or down whole number of uniquecodes whose user_id
is related to particular user's id when the user create/delete uniquecode.
How can I add the condition that I wrote above in order to exclude the uniquecodes whose community_id
is deleted (If deleted, deleted_at column will be filled with timestamp)