Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 365
Croplio Avatar asked Nov 24 '10 05:11

Croplio


2 Answers

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)
like image 184
Wayne Conrad Avatar answered Oct 14 '22 15:10

Wayne Conrad


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
like image 6
Tom Chapin Avatar answered Oct 14 '22 15:10

Tom Chapin