can_associations.rb 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. # Copyright (C) 2012-2016 Zammad Foundation, http://zammad-foundation.org/
  2. module ApplicationModel::CanAssociations
  3. extend ActiveSupport::Concern
  4. =begin
  5. set relations of model based on params
  6. model = Model.find(1)
  7. result = model.associations_from_param(params)
  8. returns
  9. result = true|false
  10. =end
  11. def associations_from_param(params)
  12. # special handling for group access association
  13. {
  14. groups: :group_names_access_map=,
  15. group_ids: :group_ids_access_map=
  16. }.each do |param, setter|
  17. map = params[param]
  18. next if map.blank?
  19. next if !respond_to?(setter)
  20. send(setter, map)
  21. end
  22. # set relations by id/verify if ref exists
  23. self.class.reflect_on_all_associations.map do |assoc|
  24. assoc_name = assoc.name
  25. next if association_attributes_ignored.include?(assoc_name)
  26. real_ids = assoc_name[0, assoc_name.length - 1] + '_ids'
  27. real_ids = real_ids.to_sym
  28. next if !params.key?(real_ids)
  29. list_of_items = params[real_ids]
  30. if !params[real_ids].instance_of?(Array)
  31. list_of_items = [ params[real_ids] ]
  32. end
  33. list = []
  34. list_of_items.each do |item_id|
  35. next if !item_id
  36. lookup = assoc.klass.lookup(id: item_id)
  37. # complain if we found no reference
  38. if !lookup
  39. raise ArgumentError, "No value found for '#{assoc_name}' with id #{item_id.inspect}"
  40. end
  41. list.push item_id
  42. end
  43. send("#{real_ids}=", list)
  44. end
  45. # set relations by name/lookup
  46. self.class.reflect_on_all_associations.map do |assoc|
  47. assoc_name = assoc.name
  48. next if association_attributes_ignored.include?(assoc_name)
  49. real_ids = assoc_name[0, assoc_name.length - 1] + '_ids'
  50. next if !respond_to?(real_ids)
  51. real_values = assoc_name[0, assoc_name.length - 1] + 's'
  52. real_values = real_values.to_sym
  53. next if !respond_to?(real_values)
  54. next if !params[real_values]
  55. next if !params[real_values].instance_of?(Array)
  56. list = []
  57. class_object = assoc.klass
  58. params[real_values].each do |value|
  59. lookup = nil
  60. if class_object == User
  61. if !lookup
  62. lookup = class_object.lookup(login: value)
  63. end
  64. if !lookup
  65. lookup = class_object.lookup(email: value)
  66. end
  67. else
  68. lookup = class_object.lookup(name: value)
  69. end
  70. # complain if we found no reference
  71. if !lookup
  72. raise ArgumentError, "No lookup value found for '#{assoc_name}': #{value.inspect}"
  73. end
  74. list.push lookup.id
  75. end
  76. send("#{real_ids}=", list)
  77. end
  78. end
  79. =begin
  80. get relations of model based on params
  81. model = Model.find(1)
  82. attributes = model.attributes_with_association_ids
  83. returns
  84. hash with attributes and association ids
  85. =end
  86. def attributes_with_association_ids
  87. key = "#{self.class}::aws::#{id}"
  88. cache = Cache.get(key)
  89. return cache if cache
  90. attributes = self.attributes
  91. relevant = %i(has_and_belongs_to_many has_many)
  92. eager_load = []
  93. pluck = []
  94. keys = []
  95. self.class.reflect_on_all_associations.each do |assoc|
  96. next if relevant.exclude?(assoc.macro)
  97. assoc_name = assoc.name
  98. next if association_attributes_ignored.include?(assoc_name)
  99. eager_load.push(assoc_name)
  100. pluck.push("#{assoc.table_name}.id")
  101. keys.push("#{assoc_name.to_s.singularize}_ids")
  102. end
  103. if eager_load.present?
  104. ids = self.class.eager_load(eager_load)
  105. .where(id: id)
  106. .pluck(*pluck)
  107. if keys.size > 1
  108. values = ids.transpose.map(&:compact).map(&:uniq)
  109. attributes.merge!( keys.zip( values ).to_h )
  110. else
  111. attributes[ keys.first ] = ids.compact
  112. end
  113. end
  114. # special handling for group access associations
  115. if respond_to?(:group_ids_access_map)
  116. attributes['group_ids'] = send(:group_ids_access_map)
  117. end
  118. filter_attributes(attributes)
  119. Cache.write(key, attributes)
  120. attributes
  121. end
  122. =begin
  123. get relation name of model based on params
  124. model = Model.find(1)
  125. attributes = model.attributes_with_association_names
  126. returns
  127. hash with attributes, association ids, association names and relation name
  128. =end
  129. def attributes_with_association_names
  130. # get relations
  131. attributes = attributes_with_association_ids
  132. self.class.reflect_on_all_associations.map do |assoc|
  133. next if !respond_to?(assoc.name)
  134. next if association_attributes_ignored.include?(assoc.name)
  135. ref = send(assoc.name)
  136. next if !ref
  137. if ref.respond_to?(:first)
  138. attributes[assoc.name.to_s] = []
  139. ref.each do |item|
  140. if item[:login]
  141. attributes[assoc.name.to_s].push item[:login]
  142. next
  143. end
  144. next if !item[:name]
  145. attributes[assoc.name.to_s].push item[:name]
  146. end
  147. if ref.count.positive? && attributes[assoc.name.to_s].empty?
  148. attributes.delete(assoc.name.to_s)
  149. end
  150. next
  151. end
  152. if ref[:login]
  153. attributes[assoc.name.to_s] = ref[:login]
  154. next
  155. end
  156. next if !ref[:name]
  157. attributes[assoc.name.to_s] = ref[:name]
  158. end
  159. # special handling for group access associations
  160. if respond_to?(:group_names_access_map)
  161. attributes['groups'] = send(:group_names_access_map)
  162. end
  163. # fill created_by/updated_by
  164. {
  165. 'created_by_id' => 'created_by',
  166. 'updated_by_id' => 'updated_by',
  167. }.each do |source, destination|
  168. next if !attributes[source]
  169. user = User.lookup(id: attributes[source])
  170. next if !user
  171. attributes[destination] = user.login
  172. end
  173. filter_attributes(attributes)
  174. attributes
  175. end
  176. def filter_attributes(attributes)
  177. # remove forbitten attributes
  178. %w(password token tokens token_ids).each do |item|
  179. attributes.delete(item)
  180. end
  181. end
  182. =begin
  183. reference if association id check
  184. model = Model.find(123)
  185. attributes = model.association_id_validation('attribute_id', value)
  186. returns
  187. true | false
  188. =end
  189. def association_id_validation(attribute_id, value)
  190. return true if value.nil?
  191. attributes.each do |key, _value|
  192. next if key != attribute_id
  193. # check if id is assigned
  194. next if !key.end_with?('_id')
  195. key_short = key.chomp('_id')
  196. self.class.reflect_on_all_associations.map do |assoc|
  197. next if assoc.name.to_s != key_short
  198. item = assoc.class_name.constantize
  199. return false if !item.respond_to?(:find_by)
  200. ref_object = item.find_by(id: value)
  201. return false if !ref_object
  202. return true
  203. end
  204. end
  205. true
  206. end
  207. private
  208. def association_attributes_ignored
  209. @association_attributes_ignored ||= self.class.instance_variable_get(:@association_attributes_ignored) || []
  210. end
  211. # methods defined here are going to extend the class, not the instance of it
  212. class_methods do
  213. =begin
  214. serve methode to ignore model attribute associations
  215. class Model < ApplicationModel
  216. include AssociationConcern
  217. association_attributes_ignored :users
  218. end
  219. =end
  220. def association_attributes_ignored(*attributes)
  221. @association_attributes_ignored ||= []
  222. @association_attributes_ignored |= attributes
  223. end
  224. =begin
  225. do name/login/email based lookup for associations
  226. params = {
  227. login: 'some login',
  228. firstname: 'some firstname',
  229. lastname: 'some lastname',
  230. email: 'some email',
  231. organization: 'some organization',
  232. roles: ['Agent', 'Admin'],
  233. }
  234. attributes = Model.association_name_to_id_convert(params)
  235. returns
  236. attributes = params # params with possible lookups
  237. attributes = {
  238. login: 'some login',
  239. firstname: 'some firstname',
  240. lastname: 'some lastname',
  241. email: 'some email',
  242. organization_id: 123,
  243. role_ids: [2,1],
  244. }
  245. =end
  246. def association_name_to_id_convert(params)
  247. if params.respond_to?(:permit!)
  248. params = params.permit!.to_h
  249. end
  250. data = {}
  251. params.each do |key, value|
  252. data[key.to_sym] = value
  253. end
  254. data.symbolize_keys!
  255. available_attributes = attribute_names
  256. reflect_on_all_associations.map do |assoc|
  257. assoc_name = assoc.name
  258. value = data[assoc_name]
  259. next if !value # next if we do not have a value
  260. ref_name = "#{assoc_name}_id"
  261. # handle _id values
  262. if available_attributes.include?(ref_name) # if we do have an _id attribute
  263. next if data[ref_name.to_sym] # next if we have already the _id filled
  264. # get association class and do lookup
  265. class_object = assoc.klass
  266. lookup = nil
  267. if class_object == User
  268. if value.instance_of?(String)
  269. if !lookup
  270. lookup = class_object.lookup(login: value)
  271. end
  272. if !lookup
  273. lookup = class_object.lookup(email: value)
  274. end
  275. else
  276. raise ArgumentError, "String is needed as ref value #{value.inspect} for '#{assoc_name}'"
  277. end
  278. else
  279. lookup = class_object.lookup(name: value)
  280. end
  281. # complain if we found no reference
  282. if !lookup
  283. raise ArgumentError, "No lookup value found for '#{assoc_name}': #{value.inspect}"
  284. end
  285. # release data value
  286. data.delete(assoc_name)
  287. # remember id reference
  288. data[ref_name.to_sym] = lookup.id
  289. next
  290. end
  291. next if !value.instance_of?(Array)
  292. next if value.empty?
  293. next if !value[0].instance_of?(String)
  294. # handle _ids values
  295. next if !assoc_name.to_s.end_with?('s')
  296. ref_names = "#{assoc_name.to_s.chomp('s')}_ids"
  297. generic_object_tmp = new
  298. next unless generic_object_tmp.respond_to?(ref_names) # if we do have an _ids attribute
  299. next if data[ref_names.to_sym] # next if we have already the _ids filled
  300. # get association class and do lookup
  301. class_object = assoc.klass
  302. lookup_ids = []
  303. value.each do |item|
  304. lookup = nil
  305. if class_object == User
  306. if item.instance_of?(String)
  307. if !lookup
  308. lookup = class_object.lookup(login: item)
  309. end
  310. if !lookup
  311. lookup = class_object.lookup(email: item)
  312. end
  313. else
  314. raise ArgumentError, "String is needed in array ref as ref value #{value.inspect} for '#{assoc_name}'"
  315. end
  316. else
  317. lookup = class_object.lookup(name: item)
  318. end
  319. # complain if we found no reference
  320. if !lookup
  321. raise ArgumentError, "No lookup value found for '#{assoc_name}': #{item.inspect}"
  322. end
  323. lookup_ids.push lookup.id
  324. end
  325. # release data value
  326. data.delete(assoc_name)
  327. # remember id reference
  328. data[ref_names.to_sym] = lookup_ids
  329. end
  330. data
  331. end
  332. end
  333. end