【问题标题】:In rubyonrails, how to get the associated model class from and ActiveRecord::Relation object?在 ruby​​onrails 中,如何从 ActiveRecord::Relation 对象中获取关联的模型类?
【发布时间】:2011-05-14 21:53:32
【问题描述】:

假设我有一个模型:

class Post
end  

posts = Post.where(***)  
puts posts.class # => ActiveRecord::Relation  

那我如何通过变量'posts'获取模型类名,也许是一些叫做model_class_name的方法:
puts posts.model_class_name # => 发布

谢谢:)

【问题讨论】:

    标签: ruby-on-rails activerecord model classname relation


    【解决方案1】:

    ActiveRecord::Relation 的#klass 属性返回建立关系的模型类:

    arel = User.where(name: "fred")
    arel.klass    # User
    

    获取班级名称:

    arel.klass.name
    

    众所周知,这适用于这些版本:

    • 最初在 ActiveRecord 4.2.4 中测试。
    • 在 Rails 5.2 中工作 (@Raphael Souza)

    【讨论】:

      【解决方案2】:

      对于有效的解决方案,即使没有相关项目:

      class Post < ActiveRecord::Base
         has_many :comments
      end
      
      Post.reflect_on_association(:comments).klass
      => Comment
      

      【讨论】:

      • 使用options: { class_name: 'AnotherClass' }时不起作用
      【解决方案3】:

      对您的问题最简单直接的回答是:

      posts.first.class.name
      

      相当于写:

      posts.[0].class.name
      

      您可以这样做,因为您的查询将返回一个可枚举的结果。 (ActiveRecord::Relation 实现了 Ruby 的 Enumerable 接口)。

      -- 斯科特

      【讨论】:

      • 嘿 Croplio,4 个月过去了。这个答案解决了你的问题吗?
      • 如果posts 没有返回任何行,那么posts.first 将为零,这将不起作用。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-03
      • 2011-05-09
      • 1970-01-01
      • 2014-07-01
      • 1970-01-01
      • 2012-06-30
      • 1970-01-01
      相关资源
      最近更新 更多