-2
我有一個模型,說Child
,belongs_to
一些其他模型Parent
。例如child
可以在rails控制檯中鍵入child.parent
以獲取父項,而不是在父項模型中明確添加child_id
作爲列?如何訪問Rails模型父
我有一個模型,說Child
,belongs_to
一些其他模型Parent
。例如child
可以在rails控制檯中鍵入child.parent
以獲取父項,而不是在父項模型中明確添加child_id
作爲列?如何訪問Rails模型父
從你描述你已經得到了下面的代碼:
class Child
belongs_to Parent
end
class Parent
end
您可以撥打child.parent
因爲父foreign_key是在child
定義,而不是parent
。如果您還沒有這樣做,您需要進行數據庫遷移以添加belongs_to
關係。
你試過了嗎?另請參閱[guide](http://guides.rubyonrails.org/association_basics.html#the-belongs-to-association)。 – jvillian