加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 在运行时查找ActiveRecord类的关联?

发布时间:2020-12-16 19:30:28 所属栏目:百科 来源:网络整理
导读:我想在运行时找到ActiveRecord类的关联… 我们假设我有以下内容: class Person ActiveRecord::Base has_many :chairs has_many :pensendclass Chair ActiveRecord::Base belongs_to :personendclass Pen ActiveRecord::Base belongs_to :personend 如何在运
我想在运行时找到ActiveRecord类的关联…

我们假设我有以下内容:

class Person < ActiveRecord::Base
  has_many :chairs
  has_many :pens
end

class Chair < ActiveRecord::Base
  belongs_to :person
end

class Pen < ActiveRecord::Base
  belongs_to :person
end

如何在运行时发现Person“有很多”椅子和笔,反之亦然?我正在寻找一个返回字符串数组的方法(如果存在这样的方法).即

Person.has_many_assocations

会回来:

["chairs","pens"]

Pen.belongs_to_associations

会回来:

["person"]

我错过了这样存在的方法吗?

谢谢你的帮助.

解决方法

我认为 ActiveRecord::Reflection课程可能就是你想要的.从文档:
Account.reflect_on_all_associations             # returns an array of all associations
  Account.reflect_on_all_associations(:has_many)  # returns an array of all has_many associations

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读