Rails: get belongs_to class_name

时间:2016-08-31 18:40:58

标签: ruby-on-rails associations belongs-to

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.

3 个答案:

答案 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_keybelongs_to,因为AR不够智能,无法将user_id映射到target_id