Categories
Technology

Rails test fixtures and foreign_key

I learned something about rails fixtures that took me a while to figure out:

So the standard fixture reference example is

# In fixtures/categories.yml
about:
name: About

# In fixtures/articles.yml
one:
title: Welcome to Rails!
body: Hello world!
category: about

But what if I had in my model

class Articles < ActiveRecord::Base
belongs_to :category, foreign_key: :subject_id

I was thinking that since my Articles object only has a subject_id attribute, I would have to specify subject_id in the .yml

But nope, apparently you can just use category and rails will automatically put it into the correct foreign_key field, which in this case, is subject_id