views:

36

answers:

2

Apologies if this question is a bit daft, but are there any negative repercussions if an app has a model or models with numerous associations? For a complex app requiring a User model, for example (eg. a social networking site), it's plausible that the model could have 15+ associations (has_many :posts, has_many :messages, has_many :photos, has_many :friends and so on). If one model is heavily associated to others, does this have any negative effect on the performance of the app? And if so, what is the best way to go about minimising problems?

+2  A: 

Well, the first piece of advice I could offer would be to prototype something quickly and see how it runs.

As for a limit on associations, ActiveRecord, by default, uses lazy relationships. Thus, loading a User won't autoload Posts, Messages, Photos, Friends, etc. until you ask for them. This is usually very good for you, since you likely don't need all of their photos on the message page.

Here's a link with some tips on Optimizing ActiveRecord for some more in depth info: http://www.ibm.com/developerworks/web/library/wa-rails3/

Andy_Vulhop
+2  A: 

An association between Models in Rails is really just manipulating id values behind the scenes. These are pretty high-performance operations, especially if you've taken the time to set up foreign-key relationships if your DB supports it. ActiveRecord also doesn't load anything unless you ask for it, so normally they would be translated as a JOIN for the SQL server only if you're acting on those relationships.

As the posts, messages, photos, or friends in your example are created, ActiveRecord will set the user_id column for you automatically. That's all that is involved in a has_many association.

Premature optimization is the root of all evil. Don't worry about it until you've established a bottleneck with profiling.

Adam Lassek