从数据库中检索对象(高级数组条件) [英] Retrieving Objects from the Database (Advanced Array Conditions)

查看:36
本文介绍了从数据库中检索对象(高级数组条件)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型,其中标签通过 Tagrelationships 与其他标签连接.某个标签可能有一个父标签和几个子标签.这是标签模型:

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

Tagrelationship 模型:

The Tagrelationship-model:

      belongs_to :child,  :class_name => "Tag"
      belongs_to :parent, :class_name => "Tag"

数据库结构:标签有以下列:id、name、user_id、created_at、updated_attagrelationships 有以下列:id、parent_id、child_id、created_at、updated_at

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

数组@roottags 包含我要查找的元素.我确信有一种更简单的方法可以在一个 sql-query 中选择没有任何父元素的标签.

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.

推荐答案

这里有一个可能满足您要求的替代建议.

Here's an alternative suggestion that may meet your requirements.

不是创建一个单独的关系类,而是通过向 Tag 类添加 parent_id 来执行自连接.

Instead of creating a separate relationship class, what about performing a self-join by adding a parent_id to the Tag class.

这通过以下方式简化了关系:

This simplifies the relationships in the following ways:

class Tag < ActiveRecord::Base
  has_many :children, :class_name => "Tag", :foreign_key => "parent_id"  
  belongs_to :parent, :class_name => "Tag"

  scope :top_level, where(:parent_id => nil)
end

现在,当您想要查找没有任何父级的标签(即顶级标签)时,您只需使用过滤具有父级 ID 的标签的命名范围即可.

Now when you want to find the Tags that don't have any parents (i.e. top level tags), you can just use the named scope that filters tags that have parent ID's.

希望有所帮助.

这篇关于从数据库中检索对象(高级数组条件)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆