在rubyonrails中,如何从ActiveRecord::Relation对象中获取关联的模型类?
假设我有一个模型:
class Post
end
posts = Post.where(***)
puts posts.class # => ActiveRecord::Relation
那么如何通过变量“posts”获取模型类名称,也许是某种名为 model_class_name 的方法:
放置 posts.model_class_name # =>发帖
谢谢:)
Suppose I have an model:
class Post
end
posts = Post.where(***)
puts posts.class # => ActiveRecord::Relation
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
Thanks :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
ActiveRecord::Relation 的 #klass 属性返回关系所在的模型类构建:
获取类的名称:
已知可与这些版本一起使用:
The #klass attribute of ActiveRecord::Relation returns the model class upon which the relation was built:
To get the class's name:
This is known to work with these versions:
对于有效的解决方案,即使没有相关项目:
For a solution that works, even if there are no related items:
对您的问题最简单、最直接的回答是:
这相当于编写:
您可以这样做,因为您的查询将返回一个可枚举的结果。 (ActiveRecord::Relation 实现了 Ruby 的 Enumerable 接口)。
——斯科特
The most simple and direct answer to your question is:
Which is equivalent to writing:
You can do this because your query will return an enumerable result. (ActiveRecord::Relation implements Ruby's Enumerable interface).
-- Scott