I have a model, in which Tags are connected with other Tags through Tagrelationships. A certain Tag may have one parent-Tag and several child-Tags. This is the Tag-model:
has_many :tagrelationships, :foreign_key => "parent_id",
:dependent => :destroy
has_many :children, :through => :tagrelationships,
:source => :child
has_one :reverse_tagrelationship, :foreign_key => "child_id",
:class_name => "Tagrelationship",
:dependent => :destroy
has_one :parent, :through => :reverse_tagrelationship,
:source => :parent
The Tagrelationship-model:
belongs_to :child, :class_name => "Tag"
belongs_to :parent, :class_name => "Tag"
The database structure: tags have the following columns: id, name, user_id, created_at, updated_at tagrelationships have the columns: id, parent_id, child_id, created_at, updated_at
I couldn't find out how to pick the Tags which haven't got any parent-Tags. Of course it's possible by picking all Tags of a certain user and evaluating these in a loop:
@tags = Tag.where(:user_id => current_user)
@tags.each do |f|
if f.parent.nil?
@roottags << f
end
end
The array @roottags contains the elements I'm looking for. I'm sure there's an easier way to pick the tags without any parent-elements within one sql-query.