aboutsummaryrefslogtreecommitdiffstats
path: root/app/models/favorite.rb
blob: df894fc9036a0abba9a7d9ecf29148bed8c97d6a (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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
class Favorite < ActiveRecord::Base
  belongs_to :tweet
  counter_culture :tweet
  belongs_to :user

  scope :order_by_id, -> do
    order("id DESC")
  end

  def user
    User.cached(user_id)
  end

  def tweet
    Tweet.cached(tweet_id)
  end

  def self.from_hash(hash)
    begin
      f = create!(tweet_id: hash[:tweet_id],
                  user_id: hash[:user_id])
      logger.debug("Created Favorite: #{hash[:user_id]} => #{hash[:tweet_id]}")

      return f
    rescue ActiveRecord::RecordNotUnique
      logger.debug("Duplicate Favorite: #{hash[:user_id]} => #{hash[:tweet_id]}")
    rescue
      logger.error("Unknown error while inserting favorite: #{$!}/#{$@}")
    end
  end

  def self.from_tweet_object(tweet_object)
    if tweet_object.favoriters.is_a? Array
      tweet_object.favoriters.reverse.map do |uid|
        from_hash(user_id: uid, tweet_id: tweet_object.id)
      end
    end
  end

  def self.delete_from_hash(hash)
    where(tweet_id: hash[:tweet_id])
      .where(user_id: hash[:user_id])
      .destroy_all
  end
end