2020-07-22 23:35:43 +00:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
# La diferencia con MetadataRelatedPosts es que la relación también
|
|
|
|
# actualiza los Posts remotos.
|
|
|
|
#
|
|
|
|
# Localmente tenemos un Array de UUIDs. Remotamente tenemos una String
|
|
|
|
# apuntando a un Post, que se mantiene actualizado como el actual.
|
|
|
|
class MetadataHasMany < MetadataRelatedPosts
|
|
|
|
# Todos los Post relacionados
|
2023-10-06 13:11:30 +00:00
|
|
|
#
|
|
|
|
# @return [Array<Post>]
|
2020-07-22 23:35:43 +00:00
|
|
|
def has_many
|
2021-05-13 22:48:41 +00:00
|
|
|
return default_value if value.blank?
|
|
|
|
|
2023-10-06 13:11:30 +00:00
|
|
|
posts.where(post_id: value).map(&:post)
|
2020-07-22 23:35:43 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
# La relación anterior
|
2023-10-06 13:11:30 +00:00
|
|
|
#
|
|
|
|
# @return [Array<Post>]
|
2020-07-22 23:35:43 +00:00
|
|
|
def had_many
|
2021-05-13 22:48:41 +00:00
|
|
|
return default_value if value_was.blank?
|
2020-07-22 23:35:43 +00:00
|
|
|
|
2023-10-06 13:11:30 +00:00
|
|
|
posts.where(post_id: value_was).map(&:post)
|
2020-07-22 23:35:43 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
def inverse?
|
|
|
|
inverse.present?
|
|
|
|
end
|
|
|
|
|
|
|
|
# La relación inversa
|
|
|
|
#
|
|
|
|
# @return [Nil,Symbol]
|
|
|
|
def inverse
|
2020-11-27 23:51:56 +00:00
|
|
|
@inverse ||= layout.metadata.dig(name, 'inverse')&.to_sym
|
2020-07-22 23:35:43 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
# Actualizar las relaciones inversas. Hay que buscar la diferencia
|
|
|
|
# entre had y has_many.
|
|
|
|
def save
|
2021-02-11 19:16:25 +00:00
|
|
|
super
|
2020-07-22 23:35:43 +00:00
|
|
|
|
2021-02-11 19:16:25 +00:00
|
|
|
return true unless changed?
|
2020-07-22 23:35:43 +00:00
|
|
|
return true unless inverse?
|
|
|
|
|
|
|
|
(had_many - has_many).each do |remove|
|
2021-02-11 19:16:25 +00:00
|
|
|
remove[inverse]&.value = remove[inverse].default_value
|
2020-07-22 23:35:43 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
(has_many - had_many).each do |add|
|
2021-02-11 19:16:25 +00:00
|
|
|
add[inverse]&.value = post.uuid.value
|
2020-07-22 23:35:43 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
true
|
|
|
|
end
|
|
|
|
|
|
|
|
def related_posts?
|
|
|
|
true
|
|
|
|
end
|
|
|
|
|
|
|
|
def related_methods
|
|
|
|
@related_methods ||= %i[has_many had_many].freeze
|
|
|
|
end
|
|
|
|
end
|