can_cleanup_param.rb 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. # Copyright (C) 2012-2016 Zammad Foundation, http://zammad-foundation.org/
  2. module ApplicationModel::CanCleanupParam
  3. extend ActiveSupport::Concern
  4. # methods defined here are going to extend the class, not the instance of it
  5. class_methods do
  6. =begin
  7. remove all not used model attributes of params
  8. result = Model.param_cleanup(params)
  9. for object creation, ignore id's
  10. result = Model.param_cleanup(params, true)
  11. returns
  12. result = params # params with valid attributes of model
  13. =end
  14. def param_cleanup(params, new_object = false)
  15. if params.respond_to?(:permit!)
  16. params = params.permit!.to_h
  17. end
  18. if params.nil?
  19. raise ArgumentError, "No params for #{self}!"
  20. end
  21. data = {}
  22. params.each do |key, value|
  23. data[key.to_sym] = value
  24. end
  25. # ignore id for new objects
  26. if new_object && params[:id]
  27. data.delete(:id)
  28. end
  29. # only use object attributes
  30. clean_params = {}
  31. new.attributes.each do |attribute, _value|
  32. next if !data.key?(attribute.to_sym)
  33. # check reference records, referenced by _id attributes
  34. reflect_on_all_associations.map do |assoc|
  35. class_name = assoc.options[:class_name]
  36. next if !class_name
  37. name = "#{assoc.name}_id".to_sym
  38. next if !data.key?(name)
  39. next if data[name].blank?
  40. next if assoc.klass.lookup(id: data[name])
  41. raise ArgumentError, "Invalid value for param '#{name}': #{data[name].inspect}"
  42. end
  43. clean_params[attribute.to_sym] = data[attribute.to_sym]
  44. end
  45. # we do want to set this via database
  46. filter_unused_params(clean_params)
  47. end
  48. private
  49. =begin
  50. remove all not used params of object (per default :updated_at, :created_at, :updated_by_id and :created_by_id)
  51. result = Model.filter_unused_params(params)
  52. returns
  53. result = params # params without listed attributes
  54. =end
  55. def filter_unused_params(data)
  56. # we do want to set this via database
  57. [:action, :controller, :updated_at, :created_at, :updated_by_id, :created_by_id, :updated_by, :created_by].each do |key|
  58. data.delete(key)
  59. end
  60. data
  61. end
  62. end
  63. end