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

Suppose I have a 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 # => Message

Thank:)

+3
source share
2 answers

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

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

To get the class name:

arel.klass.name

Tested in ActiveRecord 4.2.4

+3
source

:

posts.first.class.name

:

posts.[0].class.name

, . (ActiveRecord:: Relation Ruby Enumerable).

-

0

Source: https://habr.com/ru/post/1776624/


All Articles