2016-08-31 22 views
1

我有一個基類Entry,有很多不同的子類。如:Rails:get belongs_to class_name

class Entry < ActiveRecord::Base 
    ... 
end 

class UserEntry < Entry 
    belongs_to :target, class_name: User 
end 

有沒有一種方法來檢索target協會UserEntry類的class_name?它應該返回User

回答

1

我想我找到了我要找的東西:ActiveRecord::Reflection class methods(以前的答案是有幫助的,但是沒有真正回答這個問題)

我用reflect_on_association類的方法來獲取我的:target關聯的細節。所以爲了得到我想找的東西,我做了:

UserEntry.reflect_on_association(:target).klass,它返回User類。

2

你正在做正確的事情,除了class_name應該是一個String,不Class

class UserEntry < Entry belongs_to :target, class_name: 'User' end

+0

不一定是字符串 – Ruslan

0

請確保您設置在belongs_toprimary_keyforeign_key因爲AR是沒有足夠的智慧地圖user_id分成target_id