Sha256: 4d16a231a7a57149ba31e1c9c94cf8a115ea90069a5ad0bbb03e9f98e6bf1112

Contents?: true

Size: 1.18 KB

Versions: 11

Compression:

Stored size: 1.18 KB

Contents

class Answer < ActiveRecord::Base

  belongs_to :question, :inverse_of => :answers
  belongs_to :user, :inverse_of => :answers
  
  validates_presence_of :question,
                        :user
                        
  validate :ensure_valid_choice
  validate :ensure_valid_data_type
  validate :check_multiple_answers
  
  named_scope :for_user, lambda { |user| { :conditions => {:user_id => user.id} } }
  
  def formatted_data
    question.format_data(self.data)
  end

  def to_s
    question.to_s(self.data)
  end
  
  
  private
  
  
  def ensure_valid_choice
    return if question.blank? || data.blank?
    errors.add_to_base("Invalid choice for #{question.prompt}") if question.restrict_values? && !question.choices.map(&:value).include?(self.data)
  end
  
  def ensure_valid_data_type
    return if question.blank? || data.blank?
    message = question.validate_data(data)
    errors.add_to_base("#{question.prompt} #{message}") if message
  end
  
  def check_multiple_answers
    return if question.blank? || user.blank?
    errors.add_to_base("Only one answer allowed for #{question.prompt}") if new_record? && question.answers.for_user(user).size > 0 && !question.multiple?
  end
  
end

Version data entries

11 entries across 11 versions & 1 rubygems

Version Path
census-0.5.2 app/models/answer.rb
census-0.5.0 app/models/answer.rb
census-0.4.4 app/models/answer.rb
census-0.4.3 app/models/answer.rb
census-0.4.2 app/models/answer.rb
census-0.4.1 app/models/answer.rb
census-0.4.0 app/models/answer.rb
census-0.3.1 app/models/answer.rb
census-0.3.0 app/models/answer.rb
census-0.2.1 app/models/answer.rb
census-0.2.0 app/models/answer.rb