Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does has_many require belongs_to on the other side?

If Parent has_many :children, must Child :belongs_to :parent?

like image 996
eggdrop Avatar asked May 28 '09 16:05

eggdrop


2 Answers

No, the belongs_to isn't necessary. It will mean that you won't be able to query the association from both directions, but if that's not a requirement for your app, then it's not necessary.

like image 56
Cody Caughlan Avatar answered Sep 28 '22 09:09

Cody Caughlan


As Cody says, not mandatory - but will be the 90% case.

See the Rails API Doc for ActiveRecord Associations. When you specify either has_many or belongs_to, a bunch of (helper) methods get added to your Rails Model class. The page above shows the specific methods that get added automatically in tabular format. So if you just specify one end of the association e.g. the Child, you'd only be able to use those corresponding methods from the Child model.

like image 45
Gishu Avatar answered Sep 28 '22 07:09

Gishu