繁体   English   中英

在 ruby​​onrails 中,如何从 ActiveRecord::Relation 对象获取关联的模型类?

[英]In rubyonrails, how to get the associated model class from and ActiveRecord::Relation object?

假设我有一个模型:

class Post
end  

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

那么如何通过变量“posts”获取模型类名,也许是一些名为model_class_name的方法:
puts posts.model_class_name # => Post

谢谢 :)

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

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

获取类名:

arel.klass.name

已知这适用于这些版本:

  • 最初在 ActiveRecord 4.2.4 中测试。
  • 适用于 Rails 5.2 (@Raphael Souza)

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

class Post < ActiveRecord::Base
   has_many :comments
end

Post.reflect_on_association(:comments).klass
=> Comment

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

posts.first.class.name

这相当于写:

posts.[0].class.name

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

——斯科特

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM