Add database support and model for tips

This commit is contained in:
Sebastian Serth
2020-10-07 17:42:44 +02:00
parent 85a05225ec
commit 2e1c97d87d
7 changed files with 101 additions and 1 deletions

View File

@@ -24,6 +24,8 @@ class Exercise < ApplicationRecord
has_many :tags, through: :exercise_tags
accepts_nested_attributes_for :exercise_tags
has_many :user_exercise_feedbacks
has_many :exercise_tips
has_many :tips, through: :exercise_tips
has_many :external_users, source: :user, source_type: 'ExternalUser', through: :submissions
has_many :internal_users, source: :user, source_type: 'InternalUser', through: :submissions

View File

@@ -0,0 +1,18 @@
# frozen_string_literal: true
class ExerciseTip < ApplicationRecord
belongs_to :exercise
belongs_to :tip
belongs_to :parent_exercise_tip, class_name: 'ExerciseTip', optional: true
attr_accessor :children
# Ensure no parent tip is set if current tip has rank == 1
validates :rank, exclusion: {in: [1]}, if: :parent_exercise_tip_id?
validate :tip_chain?, if: :parent_exercise_tip_id?
def tip_chain?
# Ensure each referenced parent exercise tip is set for this exercise
errors.add :parent_exercise_tip, I18n.t('activerecord.errors.messages.together', attribute: I18n.t('activerecord.attributes.exercise_tip.tip')) unless ExerciseTip.exists?(exercise: exercise, tip: parent_exercise_tip)
end
end

23
app/models/tip.rb Normal file
View File

@@ -0,0 +1,23 @@
# frozen_string_literal: true
class Tip < ApplicationRecord
include Creation
has_many :exercise_tips
has_many :exercises, through: :exercise_tips
belongs_to :file_type, optional: true
validates_presence_of :file_type, if: :example?
validate :content?
def content?
errors.add :description, I18n.t('activerecord.errors.messages.at_least', attribute: I18n.t('activerecord.attributes.tip.example')) unless [description?, example?].include?(true)
end
def to_s
if title?
"#{I18n.t('activerecord.models.tip.one')}: #{title} (#{id})"
else
"#{I18n.t('activerecord.models.tip.one')} #{id}"
end
end
end