2016-10-11 62 views
2

模型參考我有兩個活動記錄模式獲取從ActiveRecord_Associations_CollectionProxy對象

class User < ActiveRecord::Base 
    has_many :posts 
end 

class Post < ActiveRecordd:Base 
end 

我想獲取類從ActiveRecord的關聯參考。

user.posts.get_object_class 

目前,當我做

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

有沒有一種方法,我可以得到,而不必「分裂」的字符串「::」,然後constantize呢?

回答

3

使用modelklass屬性 - 它會回報你正在尋找的常數:

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

詳情請參閱apidocs

+0

太棒了!非常感謝。正是我想要的! –

+0

@PrakashRaman歡迎:) –

+0

@PrakashRaman請務必接受答案;) –