获取关联的关系类型

Get Relationship typ of an association

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

方法 'associations' 为我提供了所有关联模型 - 但我只需要过滤我想要包含的关联类型(如果我包含 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", :validate=>true}

我如何评估“:relation=>...”属性,以便我可以将其用于 select 我需要的关联类型并更正我上面的代码?或者有更好的方法来获取包含我所有过滤关联的数组?

谢谢, 迈克尔

试试这个:

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 是这里的协会名称,例如"user".

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>