I have a base class Entry
, with lots of different subclasses. Such as:
class Entry < ActiveRecord::Base
...
end
class UserEntry < Entry
belongs_to :target, class_name: User
end
Is there a way to retrieve the class_name
of the target
association of the UserEntry class? It should return User
.
答案 0 :(得分:2)
You are doing the right thing, except class_name
should be a String
, not Class
class UserEntry < Entry
belongs_to :target, class_name: 'User'
end
答案 1 :(得分:1)
我想我找到了我正在寻找的东西:ActiveRecord::Reflection类方法(之前的答案很有帮助,但没有真正回答这个问题)
我使用reflect_on_association
类方法来获取:target
关联的详细信息。所以为了得到我想要的东西,我做了:
UserEntry.reflect_on_association(:target).klass
,返回User
类。
答案 2 :(得分:0)
请务必在primary_key
中设置foreign_key
和belongs_to
,因为AR不够智能,无法将user_id
映射到target_id