You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

custom_field_enumeration.rb 2.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. # frozen_string_literal: true
  2. # Redmine - project management software
  3. # Copyright (C) 2006-2023 Jean-Philippe Lang
  4. #
  5. # This program is free software; you can redistribute it and/or
  6. # modify it under the terms of the GNU General Public License
  7. # as published by the Free Software Foundation; either version 2
  8. # of the License, or (at your option) any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with this program; if not, write to the Free Software
  17. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  18. class CustomFieldEnumeration < ApplicationRecord
  19. belongs_to :custom_field
  20. validates_presence_of :name, :position, :custom_field_id
  21. validates_length_of :name, :maximum => 60
  22. validates_numericality_of :position, :only_integer => true
  23. before_create :set_position
  24. scope :active, lambda {where(:active => true)}
  25. def to_s
  26. name.to_s
  27. end
  28. def objects_count
  29. custom_values.count
  30. end
  31. def in_use?
  32. objects_count > 0
  33. end
  34. alias :destroy_without_reassign :destroy
  35. def destroy(reassign_to=nil)
  36. if reassign_to
  37. custom_values.update_all(:value => reassign_to.id.to_s)
  38. end
  39. destroy_without_reassign
  40. end
  41. def custom_values
  42. custom_field.custom_values.where(:value => id.to_s)
  43. end
  44. def self.update_each(custom_field, attributes)
  45. transaction do
  46. attributes.each do |enumeration_id, enumeration_attributes|
  47. enumeration = custom_field.enumerations.find_by_id(enumeration_id)
  48. if enumeration
  49. if block_given?
  50. yield enumeration, enumeration_attributes
  51. else
  52. enumeration.attributes = enumeration_attributes
  53. end
  54. unless enumeration.save
  55. raise ActiveRecord::Rollback
  56. end
  57. end
  58. end
  59. end
  60. end
  61. def self.fields_for_order_statement(table=nil)
  62. table ||= table_name
  63. columns = ['position']
  64. columns.uniq.map {|field| "#{table}.#{field}"}
  65. end
  66. private
  67. def set_position
  68. max = self.class.where(:custom_field_id => custom_field_id).maximum(:position) || 0
  69. self.position = max + 1
  70. end
  71. end