Either I’m really tired and just can’t get the juices flowing tonight, or I think that I may have found something seemingly elementary that Rails’ ActiveRecord can’t do easily or automatically. I say easily or automatically because after all, if I wanted to I could extend the ActiveRecord methods and do it myself, but that’d require some significant thought, and knowing me, I’d likely break something.
So here’s the situation that’s driving me into a wall.
I have two models, one called Instance, and the other User.
Instance represents a single discrete game in llor.nu. There are a bunch of other models (one of which I’ll get into) that look to Instance, including User. A User belongs to an Instance. There’s a column in the table called instance_id and the value in that column is the Instance that this user should be tied to.
So far, this is totally normal stuff.
When a User joins an Instance, they also have a bank account for that Instance called Account and Deeds and UserItems and so forth. This too is pretty normal stuff. User belongs to Instance, Accounts belongs to Instance, Deeds belong to User and Instance, and so on.
Here’s where it gets tricky. A User can choose to play in a different Instance. The instance_id field is set to the new id of the Instance. At this point you’re probably getting the idea of where I’m hitting some trouble. While my model relationships state that a User has one Account, it’s only true if there is one Instance. If there is more than one instance, then a User actually has more than one Account. If there’s more than one Account, I have no way of easily doing something like…
user.account
…and having it bring back the right Account, knowing which Instance the user is currently assigned to. The same problem exists for any model that belongs to a User.
Now I know there are tricks, like doing association extensions and such, but I’m not experienced enough with those tricks to feel like I have an easy solution. I’ve heard of some of the new association techniques in edge rails (like :through) but again, they’re too new to make sense to me yet.
If you’ve run into this kind of thing, what did you?