本文介绍了在rubyonrails,如何从和ActiveRecord的获得相关的模型类::关系对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个模型:

class Post
end  

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

那么,我怎么能够通过可变帖子,也许有些方法被称为model_class_name获取模型类的名称:
    把posts.model_class_name#=>发布

Then how can I get the model class name through the variable 'posts', maybe some method called model_class_name:
puts posts.model_class_name # => Post

感谢:)

推荐答案

中的返回模型类赖以关系建:

The #klass attribute of ActiveRecord::Relation returns the model class upon which the relation was built:

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

要获取类的名称:

arel.klass.name

在测试ActiveRecord的4.2.4

Tested in ActiveRecord 4.2.4

这篇关于在rubyonrails,如何从和ActiveRecord的获得相关的模型类::关系对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 11:46