views:

90

answers:

1

In associations between different models, one can avoid setting foreign key IDs directly by using fixture names as in this answer. What about self-referencing associations, such as when using acts_as_tree? Trying this:

# categories.yml
forsale:
  name: For Sale
  parent_id: nil

books:
  name: Books
  parent: forsale

I get this error:

SQLite3::SQLException: table categories has no column named parent: INSERT INTO "categories" ("name", "parent") VALUES ('Books', 'forsale')

Is there any way to make one fixtures refence another in the same class without using explicit IDs?

Update:

Appending the class name between parentheses like for polymorphic belongs_to fixtures doesn't work either. Doing this:

books:
  name: Books
  parent: forsale (Category)

Produces a random parent_id for books instead of forsale's ID.

+1  A: 

I've done this several times and can't tell why it's not working for you. The fixtures look correct as you have them (without the polymorphic (Category)). Does the association work in the rest of your app? What version of Rails are you using? You should have something like this in your Category model:

belongs_to :parent, :class_name => "Category"

If you want to just force it to work you can set an explicit parent_id like this:

books:
  name: Books
  parent_id: <%= Fixtures.identify :forsale %>

but that's obviously less than ideal...

Alex Reisner
I ran into this as well, sometimes your associations aren't quit perfect.
Garrett