2012-07-24 54 views
6

假设我有一个A型模型和一个B型模型,它有字段a_id a2_id。我想有类似的东西:Rails multiple belongs_to for same class

class B 
    belongs_to :a 
    belongs_to :a (using a2) 
end 

有谁知道我该怎么做?我正尝试使用类B来链接我的数据库中的类似对象。

回答

6

你可以做到这一点

class B 
    belongs_to :a 
    belongs_to :a2, foreign_key: 'a2_id', class_name: 'A' 
end 
+0

感谢我今晚试试这个。 – joncalhoun 2012-07-24 22:05:22

2

,甚至这样的:

class B < ActiveRecord::Base 
    attr_accessible :a2_id, :a_id, :name 
    belongs_to :a 
    belongs_to :a2, class_name: "A" 
end