Prakash Raman Prakash Raman - 1 month ago 7
Ruby Question

Get a model reference from ActiveRecord_Associations_CollectionProxy object

I have two Active Record Models

class User < ActiveRecord::Base
has_many :posts
end

class Post < ActiveRecordd:Base
end


I would like to get the reference of the class Post from the activerecord association.

user.posts.get_object_class


Currently when I do

user.posts.class.to_s
# Post::ActiveRecord_Associations_CollectionProxy


Is there a way I can get Post without having to "split" the string on "::" and then constantize it ?

Answer

Use model or klass attribute - it will return the constant you are looking for:

user.posts.model
#=> Post
user.posts.klass
#=> Post

See apidocs for more details.

Comments