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

发布于 2024-10-04 06:56:36 字数 254 浏览 0 评论 0原文

假设我有一个模型:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

南薇 2024-10-11 06:56:36

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

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

获取类的名称:

arel.klass.name

已知可与这些版本一起使用:

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

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

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

To get the class's name:

arel.klass.name

This is known to work with these versions:

  • Originally tested in ActiveRecord 4.2.4.
  • Works in Rails 5.2 (@Raphael Souza)
中性美 2024-10-11 06:56:36

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

class Post < ActiveRecord::Base
   has_many :comments
end

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

For a solution that works, even if there are no related items:

class Post < ActiveRecord::Base
   has_many :comments
end

Post.reflect_on_association(:comments).klass
=> Comment
可是我不能没有你 2024-10-11 06:56:36

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

posts.first.class.name

这相当于编写:

posts.[0].class.name

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

——斯科特

The most simple and direct answer to your question is:

posts.first.class.name

Which is equivalent to writing:

posts.[0].class.name

You can do this because your query will return an enumerable result. (ActiveRecord::Relation implements Ruby's Enumerable interface).

-- Scott

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文