我有两个模型,一个带有问题,可以在调查表中动态添加问题,另一个带有答案。 答案显示在答案表的单独页面上-因此它们与问题无关。每个答案中只有一个问题ID。 我的任务是在创建新的审核之前检查所有答案,如果对于至少一个答案没有疑问,则将引发错误,并且如果用户单击“取消”,将破坏审核。
我这样尝试,但是不起作用
# frozen_string_literal: true
module Audits
# Service that create audit with answers
# only if all answers present.
class CreateService < ApplicationService
attr_accessor :audit
def initialize(audit)
@audit = audit
end
def call
if check_for_answers == audit.checklist.cout_questions
audit.create
else
audit.destroy
end
end
private
def check_for_answers
audit.answers.count
end
end
end
class Checklist < ApplicationRecord
# Checklist can have many questions and when delete a checklist
# the question that belongs to the specific checklist will be deleted as well.
has_many :questions, dependent: :destroy
has_many :audits, dependent: :destroy
validates :title, presence: true
validates :description, presence: true
# @return [Integer] sum of all questions in the current list
def count_questions
questions.count
end
end
审核模型
class Audit < ApplicationRecord
belongs_to :checklist
has_many :answers, dependent: :destroy
end
问题模型:
class Question < ApplicationRecord
# Question belongs to a checklist
belongs_to :checklist
validates :title, presence: true, length: { in: 12..40 }
validates :description, presence: true
end
答案模型:
class Answer < ApplicationRecord
# Default answers for questions
DEFAULT_ANSWER = ['Yes', 'No', 'N/A']
belongs_to :audit
validates :answer, presence: true
validates :comment, presence: true, length: { maximum: 40 }
end