aboutsummaryrefslogtreecommitdiffstats
path: root/app/models/favorite.rb
blob: 7d0f1a1add1693bf054d5bb353faabd5a0d1ad88 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Favorite < ActiveRecord::Base
  belongs_to :tweet
  belongs_to :user

  after_create do
    Tweet.update_counters(self.tweet_id, favorites_count: 1, reactions_count: 1)
  end

  after_destroy do
    Tweet.update_counters(self.tweet_id, favorites_count: -1, reactions_count: -1)
  end

  def self.from_receiver(msg)
    transaction do
      t = Tweet.from_receiver(msg["target_object"])
      u = User.from_receiver(msg["source"])
      f = t.favorites.new(user: u)
      f.save_ignore!
      logger.debug("Created Favorite: #{msg["source"]["id"]} => #{msg["target_object"]["id"]}")
      return f
    end
  rescue => e
    logger.error("Unknown error while inserting favorite: #{e.class}: #{e.message}/#{e.backtrace.join("\n")}")
    return nil
  end

  def self.delete_from_receiver(msg)
    where(tweet_id: msg["target_object"]["id"], user_id: msg["source"]["id"]).destroy_all
  end
end