rails: Fixtures not working with single table inheritance

I’ve found that when using single table inheritance it’s necessary to use a single fixture file for all the test objects of that particular inheritance tree. For example when using a base class Person and Two child classes Student and Teacher, the expected behavior would be that when loading the files teacher.yml and students.yml the table people would have all the fixtures in it. The following are some simple files to explain it.

#teachers.yml
presto:
    name: Test Teacher
#students.yml
testo:
    name: Test Person
    teacher: presto

However when loading this fixtures only the teacher fixture exists in the database, after some messing around with the fixtures API and console I found that only the last fixtures of the table are that ones that are kept, which in default behaviour is the teachers fixtures because of the alphabetical loading order. Moreover, if the last fixture file is an empty one, the table stays empty.

Maybe I didn’t find it, but when researching it I saw no mention of this behavior in the docs.

The workaround I’ve found to work, is to use a single fixture file for any table that uses single table inheritance and erasing all other fixture files for the subclasses, or to load them explicitly by calling the fixtures API.

About this issue

  • Original URL
  • State: closed
  • Created 9 years ago
  • Reactions: 1
  • Comments: 17 (7 by maintainers)

Commits related to this issue

Most upvoted comments

For anyone still running into this problem you need to add a type attribute to your fixtures, which represents the STI attribute on your model. For the provided example this would be:

#teachers.yml
presto:
    name: Test Teacher
    type: Teacher
#students.yml
testo:
    name: Test Person
    teacher: presto
    type: Student

At least I haven’t found a way to avoid this. Happy coding!

I can confirm this issue on master. This is happening because we are not merging the rows for STI tables - https://github.com/rails/rails/blob/master/activerecord/lib/active_record/fixtures.rb#L526 and deleting previous rows before addings rows in same table(in case of STI only)- https://github.com/rails/rails/blob/master/activerecord/lib/active_record/fixtures.rb#L528-L530