Post

Ruby on Rails: How to use a fixture inside of another fixture

Ruby on Rails: How to use a fixture inside of another fixture

The Example

For this example, I am going to use Authors and Books. Authors have many books, and each book has one author.

1
2
3
4
5
6
7
class Book < ApplicationRecord
  belongs_to :author
end

class Author < ApplicationRecord
  has_many :books, dependent: :destroy
end

Because of how has_many works, we must store a reference to the author in the book model. As seen in the Rails documentation.

1
2
3
4
5
author1:
  name: "Author One"
book1:
  name: "Book One"
  author_id: ???

But what should we put instead of ????
If we try to use author_id: <%= Author.find_by(name: "Author One").id %> we would have to query the database, which is impractical for large fixtures.

The solution

As seen in the ActiveRecord API:
Active Record reflects on the fixture’s model class, finds all the belongs_to associations, and allows you to specify a target label for the association (monkey: george) rather than a target id for the FK (monkey_id: 1)

So if we want the fixture label “author1” to be the author of “book1”:

1
2
3
book1:
  name: "Book One"
  author: author1
This post is licensed under CC BY-NC 4.0 by the author.