validation - How to avoid to update record in self referenced model due to not refers to itself and also not to be duplicate references -
i have self referenced model:
class component < activerecord::base has_and_belongs_to_many :allergens has_many :cqnames, as: :cqnable has_many :inclusions has_many :ingredients, :through => :inclusions accepts_nested_attributes_for :cqnames, allow_destroy: true accepts_nested_attributes_for :ingredients accepts_nested_attributes_for :inclusions, allow_destroy: true translates :name, :description validates :name, presence: true, uniqueness: true def self.get_children(ing) @tree ||= [] if ing.ingredients.nil? return @tree else @tree << ing.ingredients get_children(ing.ingredients) end end end
i have avoid self referencing same record , records referenced when respecting record updating.
experiment before_validation...:
class component < activerecord::base before_validation :hokus has_and_belongs_to_many :allergens has_many :cqnames, as: :cqnable has_many :inclusions has_many :ingredients, :through => :inclusions has_many :inverse_inclusions, :class_name => "inclusion", :foreign_key => "ingredient_id" has_many :composites, :through => :inverse_inclusions, :source => :component accepts_nested_attributes_for :cqnames, allow_destroy: true accepts_nested_attributes_for :ingredients accepts_nested_attributes_for :inclusions, allow_destroy: true translates :name, :description validates :name, presence: true, uniqueness: true require 'set' def self.pokus(ing) avoid = set.new([self]) q = true if ing.ingredients.present? ing.ingredients.each |record| q = false if avoid.include? record end end q end def hokus component.pokus(self) end end
if want simpler version should job done may do.
require 'set' def self.get_children(ing) tree = set.new recursive = lambda {|recs| recs.ingredients.each |record| recursive.call(record.ingredients) if tree.add?(record) end } recursive.call(ing.ingredients) tree.to_a end
Comments
Post a Comment