Blog ยป Rails: Match each has_many with a belongs_to
Posted on 25 Feb 2011 21:53
Matching each belongs_to to a has_many might be tedious. You can check it on the bash shell:
A=parent_class; B=child_class; grep -R :$B app/models/*.rb | grep has_many | grep $A; grep -R :$A app/models/*.rb | grep $B
Then you'll see clearly parent and child classes are matching:
./parent_class.rb: has_many :child_classes, :dependent=>:destroy ./child_class.rb: belongs_to :parent_class
And of course you did not forget :dependent option, right?
Each has_many in your application should be one of those if it's not :through
A) Parent has to destroy it's children
./parent_class.rb: has_many :child_classes, :dependent=>:destroy
B) Children forgets parent
./parent_class.rb: has_many :child_classes, :dependent=>:nullify
C) Parent is in use. It cannot be destroyed:
./parent_class.rb: has_many :child_classes, :dependent=>:restrict
If your version of Rails do not have :restrict option then you can:
./parent_class.rb: has_many :child_classes, :nullify def destroy super if child_classes.empty? end
Finally, it's a wise idea to peer review all has_many's in the application
grep -R has_many app/models/*.rb
If you like this page, please spread the word:
You can contact me if you have questions or corrections.