can_associations.rb 12 KB

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