mirror of
https://0xacab.org/sutty/sutty
synced 2024-11-26 17:16:23 +00:00
feat: establecer relaciones bidireccionales
This commit is contained in:
parent
1e2c29f309
commit
b06751e62e
2 changed files with 41 additions and 3 deletions
|
@ -40,13 +40,21 @@ class MetadataBelongsTo < MetadataRelatedPosts
|
|||
# Si estamos cambiando la relación, tenemos que eliminar la relación
|
||||
# anterior
|
||||
if belonged_to.present?
|
||||
belonged_to[inverse].value = belonged_to[inverse].value.reject do |rej|
|
||||
rej == post.uuid.value
|
||||
if belonged_to[inverse].respond_to? :has_one
|
||||
belonged_to[inverse].value = nil
|
||||
else
|
||||
belonged_to[inverse].value = belonged_to[inverse].value.reject do |rej|
|
||||
rej == post.uuid.value
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# No duplicar las relaciones
|
||||
belongs_to[inverse].value = (belongs_to[inverse].value.dup << post.uuid.value) unless belongs_to.blank? || included?
|
||||
if belongs_to[inverse].respond_to? :has_one
|
||||
belongs_to[inverse].value = post.uuid.value
|
||||
else
|
||||
belongs_to[inverse].value = (belongs_to[inverse].value.dup << post.uuid.value) unless belongs_to.blank? || included?
|
||||
end
|
||||
|
||||
true
|
||||
end
|
||||
|
|
|
@ -1,4 +1,34 @@
|
|||
# frozen_string_literal: true
|
||||
|
||||
class MetadataHasOne < MetadataHasMany
|
||||
def had_one
|
||||
return default_value if value_was.blank?
|
||||
|
||||
posts.find(uuid: value)
|
||||
end
|
||||
|
||||
def has_one
|
||||
return default_value if value.blank?
|
||||
|
||||
posts.find(uuid: value)
|
||||
end
|
||||
|
||||
def had_many; end
|
||||
def has_many; end
|
||||
|
||||
def save
|
||||
super
|
||||
|
||||
return true unless changed?
|
||||
return true unless inverse?
|
||||
|
||||
had_one&.value = nil
|
||||
has_one&.value = post.uuid.value
|
||||
|
||||
true
|
||||
end
|
||||
|
||||
def related_methods
|
||||
@related_methods ||= %i[has_one had_one].freeze
|
||||
end
|
||||
end
|
||||
|
|
Loading…
Reference in a new issue