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
|
2021-02-11 19:44:36 +00:00
|
|
|
def validate
|
|
|
|
super
|
|
|
|
|
|
|
|
errors << I18n.t('metadata.has_many.missing_posts') unless posts_exist?
|
|
|
|
|
|
|
|
errors.empty?
|
|
|
|
end
|
|
|
|
|
2020-07-22 23:35:43 +00:00
|
|
|
# Todos los Post relacionados
|
|
|
|
def has_many
|
2021-05-13 22:48:41 +00:00
|
|
|
return default_value if value.blank?
|
|
|
|
|
|
|
|
posts.where(uuid: value)
|
2020-07-22 23:35:43 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
# La relación anterior
|
|
|
|
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
|
|
|
|
2021-05-13 22:48:41 +00:00
|
|
|
posts.where(uuid: value_was)
|
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
|
2021-02-11 19:44:36 +00:00
|
|
|
|
|
|
|
def posts_exist?
|
2021-02-11 20:57:12 +00:00
|
|
|
has_many.size == sanitize(value).size
|
2021-02-11 19:44:36 +00:00
|
|
|
end
|
2020-07-22 23:35:43 +00:00
|
|
|
end
|