【问题标题】:rails method to get the association name of a modelrails 方法获取模型的关联名称
【发布时间】:2010-01-07 22:36:25
【问题描述】:

有没有办法找出模型有什么关联?采用这 2 个模型:

class Comment < ActiveRecord::Base
  belongs_to :commentable
end

class Post < ActiveRecord::Base
  has_many :comments
  belongs_to :user
end

我正在寻找类似的东西:

Post.has_many #=> ['comments', ...]
Post.belongs_to # => ['user']
Comment.belongs_to # => ['commentable']

【问题讨论】:

    标签: ruby-on-rails rails-activerecord


    【解决方案1】:

    您正在寻找reflect_on_all_associations

    简而言之:

    Post.reflect_on_all_associations(:has_many)
    

    ...将给出所有has_many 关联的数组(具有name 等属性的对象)。

    【讨论】:

      【解决方案2】:

      以下将列出特定 Post 实例的所有关联。

      #app/models/post.rb
        def list_associations
          associations = []
          User.reflect_on_all_associations.map(&:name).each do |assoc|
            association = send assoc
            associations << association if association.present?
          end
          associations
        end
      

      【讨论】:

        猜你喜欢
        • 2014-07-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-04-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多