Class: Course::Discussion::Topic

Inherits:
ApplicationRecord show all
Defined in:
app/models/course/discussion/topic.rb

Defined Under Namespace

Modules: PostsConcern Classes: Subscription

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.global_topic_modelsObject


18
19
20
# File 'app/models/course/discussion/topic.rb', line 18

def self.global_topic_models
  global_topic_model_names.map(&:constantize)
end

Instance Method Details

#ensure_subscribed_by(user) ⇒ Object

Create subscription for a user

The additional transaction is in place because a RecordNotUnique will cause the active transaction to be considered as errored, and needing a rollback.

Parameters:

  • user (User)

    The user who needs to subscribe to this topic


58
59
60
61
62
63
64
65
66
67
# File 'app/models/course/discussion/topic.rb', line 58

def ensure_subscribed_by(user)
  ApplicationRecord.transaction(requires_new: true) do
    subscribed_by?(user) || subscriptions.create!(user: user)
  end
rescue ActiveRecord::RecordInvalid, ActiveRecord::RecordNotUnique => e
  errors = e.record.errors
  return true if e.is_a?(ActiveRecord::RecordInvalid) &&
                 !errors[:topic_id].empty? && !errors[:user_id].empty?
  raise e
end

#from_userObject

Returns the topics from the user(s) specified.

@param[Integer|Array] user_id, the id(s) of the user(s). @return[ArrayCourse::Discussion::Topic]


32
33
34
35
36
37
38
# File 'app/models/course/discussion/topic.rb', line 32

scope :from_user, (lambda do |user_id|
  where(
    global_topic_models.map do |model|
      "course_discussion_topics.id IN (#{model.from_user(user_id).to_sql})"
    end.join(' OR ')
  )
end)

#mark_as_pendingObject


69
70
71
72
73
74
# File 'app/models/course/discussion/topic.rb', line 69

def mark_as_pending
  return true if pending_staff_reply

  self.pending_staff_reply = true
  save
end

#subscribed_by?(user) ⇒ Boolean

Return if a user has subscribed to this topic

Parameters:

  • user (User)

    The user to check

Returns:

  • (Boolean)

    True if the user has subscribed this topic


48
49
50
# File 'app/models/course/discussion/topic.rb', line 48

def subscribed_by?(user)
  subscriptions.where(user: user).any?
end

#unmark_as_pendingObject


76
77
78
79
80
81
# File 'app/models/course/discussion/topic.rb', line 76

def unmark_as_pending
  return true unless pending_staff_reply

  self.pending_staff_reply = false
  save
end