代码之家  ›  专栏  ›  技术社区  ›  takacsot

仅基于外键属性的关联的类是什么?

  •  13
  • takacsot  · 技术社区  · 14 年前

    简短:我有一个外键属性,想知道外键字段的类(或引用表)是什么。

    上下文:

    给出2张表格: users(id, [other fields]) issues(id, user_id, assigned_to, [other fields])

    这是我的活动记录问题(无关部分提取)

    class User < ActiveRecord::Base
      ...
    end
    class Issue < ActiveRecord::Base
      belongs_to :user
      belongs_to :assigned_user, :foreign_key => 'assigned_to', :class_name => 'User'
      ...
    end
    

    我想做一个用户可读的更改日志。e、 g.更改分配的用户时,我希望得到如下消息: Assigned to is changed from Otto to Zoltan . ActiveRecord具有 changes

    结社 :user 这很容易,因为我只需要遵守惯例。但如何获取相同的信息 assigned_to

    2 回复  |  直到 14 年前
        1
  •  33
  •   Joshua Muheim    12 年前

    首先,你可以使用 reflect_on_association MacroReflection 后代)您可以找到类:

    reflection = Issue.reflect_on_association(:assigned_user)
    reflection.class # => ActiveRecord::Reflection::AssociationReflection
    reflection.class_name # => 'User'
    

    here there

        2
  •  3
  •   takacsot    14 年前

    非常感谢。以下是针对具体问题的最终解决方案(用于学习):

      def textalize_changes
        if changed?
          r = ""
          changes.keys.each do |k|
            r << "#{k.humanize} changed "
            r << "from `#{translate(k,changes[k][0])}` " 
            r << "to `#{translate(k,changes[k][1])}`"
            r << "<br/>"
          end
          r
        end
      end
    
      def translate(attr_name, attr_value)
        ass = self.class.reflect_on_all_associations(:belongs_to).reject{|a| attr_name != a.primary_key_name}
        if 1 == ass.length and !attr_value.blank?
          obj = ass[0].klass.find(attr_value)
          obj.send(:name)
        else
          attr_value
        end
      end