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

陌路散爱 提交于 2019-12-10 17:17:31

问题


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 :)


回答1:


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

Tested in ActiveRecord 4.2.4




回答2:


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



回答3:


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



来源:https://stackoverflow.com/questions/4263844/in-rubyonrails-how-to-get-the-associated-model-class-from-and-activerecordrel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!