2017-09-25 94 views
-2

我有一個模型,說Childbelongs_to一些其他模型Parent。例如child可以在rails控制檯中鍵入child.parent以獲取父項,而不是在父項模型中明確添加child_id作爲列?如何訪問Rails模型父

+2

你試過了嗎?另請參閱[guide](http://guides.rubyonrails.org/association_basics.html#the-belongs-to-association)。 – jvillian

回答

0

從你描述你已經得到了下面的代碼:

class Child 
    belongs_to Parent 
end 

class Parent 
end 

您可以撥打child.parent因爲父foreign_key是在child定義,而不是parent。如果您還沒有這樣做,您需要進行數據庫遷移以添加belongs_to關係。