代码之家  ›  专栏  ›  技术社区  ›  Michael H.

获取关联的关系类型

  •  0
  • Michael H.  · 技术社区  · 7 年前

    我使用rails/mongoid为我的模型创建动态类。每当我访问记录时,我想自动包括某些关联的记录(属于,有一个)。因此,我需要在as\U json函数中包含所有这些关联。

    “associations”方法为我提供了所有关联的模型,但我只需要过滤我想要包含的关联类型(如果我包含has\u many关联,我将得到一个非常耗时的数据库请求,我不需要这些数据)。如何过滤association方法的输出以仅获取所需的关联?

    我试着遍历所有关联:

      def as_json(options={})
        selected_associations=[]
        associations.each do |ass|
          puts "Association:: ", ass, ass=>relation
          if association=='Belongs_To'       # Need the right instruction here
             selected_associations.push(ass) 
          end 
        end
        attrs = super(:include => selected_associations)
    
      end
    

    Puts在控制台上为每个关联提供以下输出(实体是一个模型):

    关联: 实体 {:关系=>Mongoid::关系::引用::多,:扩展=>零,:反向\u class\u name=>“WSAEntity”,:name=>“entities”,:class\u name=>“WSAEntity”,:验证=>true}

    如何评估“:关系=>…”属性,以便我可以使用它来选择所需的关联类型并更正上面的代码?或者有更好的方法获得包含所有筛选关联的数组?

    谢谢 迈克尔

    1 回复  |  直到 7 年前
        1
  •  1
  •   Jagdeep Singh    7 年前

    尝试以下操作:

    associations.each do |key, value|
      ...
      if value.macro == :belongs_to        # OR you can do `value.relation == Mongoid::Relations::Referenced::In`
        selected_associations.push(key)    # OR `value`, you need to decide what you need here
      end 
    end
    

    key 此处是关联的名称,例如“用户”。

    value 看起来像这样:

    #<Mongoid::Relations::Metadata
    autobuild:    false
    class_name:   User
    cyclic:       nil
    counter_cache:false
    dependent:    nil
    inverse_of:   nil
    key:          user_id
    macro:        belongs_to
    name:         user
    order:        nil
    polymorphic:  false
    relation:     Mongoid::Relations::Referenced::In
    setter:       user=
    versioned:    false>