Support HABTM and has_many/has_many relations.

Plus some refactoring.