11

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

Croplio
  • 3,433
  • 6
  • 31
  • 37

3 Answers3

22

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)
Wayne Conrad
  • 103,207
  • 26
  • 155
  • 191
6

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
Tom Chapin
  • 3,276
  • 1
  • 29
  • 18
0

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

Scott
  • 17,127
  • 5
  • 53
  • 64