can_associations.rb 11 KB

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