获取关联的关系类型

问题描述 投票:0回答:1

我使用rails / mongoid为我的模型创建动态类。我想在每次访问记录时自动包含某些相关记录(belongs_to,has_one)。因此,我需要在as_json函数中包含所有这些关联。

方法“关联”给了我所有相关的模型 - 但我只需要过滤我想要包含的关联类型(如果我包含has_many关联,我会得到一个耗费大量时间的数据库请求而且我不需要这些数据)。如何过滤关联方法的输出以仅获取所需的关联?

我试图遍历所有关联:

  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为我提供了每个关联(实体是一个模型):

关联:实体{:relation => Mongoid :: Relations :: Referenced :: Many,:extend => nil,:inverse_class_name =>“WSAEntity”,:name =>“entities”,:class_name =>“WSAEntity”,:验证=>真}

如何评估':relation => ...'属性,以便我可以使用它来选择我需要的关联类型并更正上面的代码?或者有一种更好的方法来获得一个包含所有过滤关联的数组?

谢谢,迈克尔

ruby-on-rails mongodb mongoid
1个回答
1
投票

试试这个:

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>
© www.soinside.com 2019 - 2024. All rights reserved.