Rails: Match each has_many with a belongs_to

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: diggdel.icio.usFacebook

You can contact me if you have questions or corrections.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License