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 :)
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:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With