Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialDaniel Crittenden
9,308 PointsI've read a criticism of the HABTM association type. Is it valid?
http://blog.flatironschool.com/why-you-dont-need-has-and-belongs-to-many/
Above is a link to a Rails developer criticizing this association method. Their argument:
"Rails Guides says that 'You should use has_many :through if you need validations, callbacks, or extra attributes on the join model.' As the great coding philosopher Avi Flombaum once eluded, how can you possibly know that your join model will not serve an additional purpose this early in the application process? No matter where you are in the development stage, you can never see so far in the future to know you will not need to extend the join table."
Is this a valid argument? Is it really a safer bet to use the "has many"/"through" method instead?
My apologies is if this is addressed later on. I will add a response to this question if that is the case.
Thank you!
1 Answer
Maciej Czuchnowski
36,441 PointsI'd probably agree with this statement. Whenever I need an association like that, I always assume that at some point in the future I may need to do something with the join model, so I personally NEVER use HABTM relation. I don't like having a join table in the database which is not represented by a model that I can customize when I need to. I like the potential flexibility, even if I'm not going to use it. This does require an extra step - creating the join model and the extra relations along the way - but it's not that much extra work. And you gain access to this join model in the console, which is great for debugging and experimenting.
Imagine that you use the HABTM relation and a few years later you realize that you actually need to do something with the join model. Imagine what it would take to refactor this and run proper migrations without losing any data. I think HABTM relation can be used in some rare cases, for example when doing very rapid prototyping, a demo app, an MVP where the data will really be expendable and temporary. I'm sure there are also real cases where you could use it, but you need absolute, 100% certainty that you know what you're doing. This comes with experience.