Using Foxy Fixtures for Polymorphic Associations in Rails 2

By Scott Roth on April 5th, 2008

Tagged with: rails, rails 2.x, fixtures, polymorphic associations

As we all know, the Rathole plugin was sucked into Rails core with the release of Rails 2 and now using fixtures has become, um, foxier.  One use case that wasn't immediately clear to me was how to specify polymorphic relationships using the new and improved syntax.  It turns out that this is straightforward.

Let's say your application captures contact information for several models.  Our hypothetical application is a brand new social network for people in the music industry.  (Quick, let's pitch it to VCs!)  Each application user would have contact information and, since they are in the music industry, they belong to a Record Label.  Record Labels also have contact information stored for them.  So we get this:

 1  class Contact < ActiveRecord::Base
2 belongs_to :contactable, :polymorphic => true
3 end
4
5 class User < ActiveRecord::Base
6 has_one :contact, :as => :contactable
7 end
8
9 class Label < ActiveRecord::Base
10 has_one :contact, :as => :contactable
11 end

Now to set up the fixtures.  All you need to do is specify the contactable name and contactable_type for each contact and we are done.

 1  # User
2 music_industry_person:
3 username: person1
4 password: secret
5
6 # Label
7 label1:
8 name = Some Indie Label
9
10 # Contact
11 fred:
12 contactable: music_industry_person
13 contactable_type: User
14 first_name: Fred
15
16 sam:
17 contactable: label1
18 contactable_type: Label
19 first_name: Sam

As you can see, a piece of cake!

Update:  Phil knew a one liner way to do this:

1  sam:
2 contactable: label1 (Label)
3 first_name: Sam

 

3 Comments

  1. Phil Matarese

    Sun April 06, 2008 at 09:04

    A piece of cake is nice, but it could even be as easy as pie...

    sam:
      contactable: label1 (Label)
      first_name: Sam

    Mmm... pie.
  2. Henry Work

    Sat October 11, 2008 at 15:24

    Scott, Phil,

    Thanks a lot for the sweet tips! I'm currently working on a side project that heavily relies on, you guessed it, fixtures (and has a ton of polymorphic associations) -- this made my erb Fixture.identify hacks much simpler. Cheers!

    -Henry
  3. Seth

    Mon October 13, 2008 at 06:16

    Yes! Very slick. Thank you for saving me from fixture hell right now.

Weigh in

(HTML tags are stripped, URLs are automatically converted to links)