answers_controller.rb 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. # Copyright (C) 2012-2023 Zammad Foundation, https://zammad-foundation.org/
  2. class KnowledgeBase::AnswersController < KnowledgeBase::BaseController
  3. include HasPublishing
  4. # accessible outside of specific Knowledge Base
  5. # /api/v1/knowledge_bases/recent_answers
  6. def recent_answers
  7. answers = KnowledgeBase::Answer.published.limit(10)
  8. render json: {
  9. assets: ApplicationModel::CanAssets.reduce(answers),
  10. answer_ids_recent_viewed: answers.pluck(:id)
  11. }
  12. end
  13. # overrides show method to return KnowledgeBase::Answer::Translation::Content when needed
  14. def show
  15. object = klass.find(params[:id])
  16. assets = object.assets({})
  17. if params[:include_contents].present?
  18. content_ids = params[:include_contents].split(',')
  19. contents = KnowledgeBase::Answer::Translation::Content.where id: content_ids
  20. assets = ApplicationModel::CanAssets.reduce contents, assets
  21. end
  22. render json: { id: object.id, assets: assets }, status: :ok
  23. end
  24. # overrides show method to return KnowledgeBase::Answer::Translation::Content for the object just created
  25. def create
  26. clean_params = klass.association_name_to_id_convert(params)
  27. clean_params = klass.param_cleanup(clean_params, true)
  28. # create object
  29. object = klass.new(clean_params)
  30. # set relations
  31. object.associations_from_param(params)
  32. # save object
  33. object.save!
  34. assets = object.assets({})
  35. contents = object.translations.filter_map(&:content)
  36. assets = ApplicationModel::CanAssets.reduce contents, assets
  37. render json: { id: object.id, assets: assets }, status: :created
  38. end
  39. # overrides show method to return KnowledgeBase::Answer::Translation::Content that was just saved
  40. def update
  41. object = klass.find(params[:id])
  42. clean_params = klass.association_name_to_id_convert(params)
  43. clean_params = klass.param_cleanup(clean_params, true)
  44. object.with_lock do
  45. # set relations
  46. object.associations_from_param(params)
  47. # set attributes
  48. object.update!(clean_params)
  49. # execute action if needed
  50. if (additional_action = params[:additional_action]&.to_sym)
  51. object.can_be_published_aasm.aasm.fire! additional_action, current_user
  52. end
  53. end
  54. assets = object.assets({})
  55. contents = object.translations.select { |e| e.content.previous_changes.any? }.map(&:content)
  56. assets = ApplicationModel::CanAssets.reduce contents, assets
  57. render json: { id: object.id, assets: assets }, status: :ok
  58. end
  59. end