Thursday, October 2, 2008

Recipe 49 gotcha (from Advanced Rails Recepies - 84 New Ways...)

Advanced Rails Recepies suggests in recipe #49 to avoid specifying IDs for fixtures when you're trying to express has_and_belongs_to_many relationships and instead just refer to the name of the instance in one of the fixtures. Looks wonderful.

I had some number of fixtures and just wanted to introduce this by adding a completely new fixture file and specifying the relationship as suggested. The old files that I had I modified by adding the relationship reference.

For example, I had a simple users.yml which had:
user1:
id: 1
name: jack

I has_and_belongs_to_many :roles for user. My roles.yml fixture was:
role1:
id: 1
name: role1
So I tried adding a reference to the role1 in my user1 like so:
user1:
id: 1
name: jack
roles: role1
The test failed when I tried verifying that user1 contains role1. It appeared that the connection was never made. I did notice in the database that a record in tables roles, users and roles_users was added but (!) the ID for roles_users.role_id was this weird big number that was obviously the reason why it appeared that the user did not get the role required.

To fix this, just remove the ID from those instances inside your fixture files that you'll be "connecting" through that nicer named-reference approach.

No comments: