poll.rb 1.14 KB
Newer Older
Benjamin Neff's avatar
Benjamin Neff committed
1
class Poll < ApplicationRecord
2
  include Diaspora::Federated::Base
3
  include Diaspora::Fields::Guid
4

5
  belongs_to :status_message
6
  has_many :poll_answers, -> { order 'id ASC' }
7
  has_many :poll_participations
8
  has_one :author, through: :status_message
9

10
  #forward some requests to status message, because a poll is just attached to a status message and is not sharable itself
11
  delegate :author_id, :diaspora_handle, :public?, :subscribers, to: :status_message
12

13
  validate :enough_poll_answers
14
  validates :question, presence: true
15

16 17
  self.include_root_in_json = false

18
  def enough_poll_answers
19
    errors.add(:poll_answers, I18n.t("activerecord.errors.models.poll.attributes.poll_answers.not_enough_poll_answers")) if poll_answers.size < 2
20 21
  end

22 23
  def as_json(options={})
    {
Rete2's avatar
Rete2 committed
24 25 26 27 28
      poll_id:             id,
      post_id:             status_message.id,
      question:            question,
      poll_answers:        poll_answers,
      participation_count: participation_count
29 30 31
    }
  end

Rete2's avatar
Rete2 committed
32 33
  def participation_answer(user)
    poll_participations.find_by(author_id: user.person.id)
34
  end
35

Rete2's avatar
Rete2 committed
36 37
  def participation_count
    poll_answers.sum("vote_count")
38
  end
39
end