I have a model with a has_one association through another model.
class Publisher
has_many :books
end
class Book
belongs_to :publisher
has_one :author
end
class Author
belongs_to :book
has_one :publisher, :through => :book
end
In my Rails code, I can call author.publisher without a problem, so that all works nicely. However in my specs (using Rspec and FactoryGirl, the association just doesn’t seem to work. Here are my FactoryGirl definitions:
Factory.define :author do |a|
a.association :book
end
Factory.define :book do |b|
b.association :publisher
end
Factory.define :publisher
end
(Omitted most of the attributes from the factories).
Now in my specs, I can do the following
pub = Factory(:publisher)
book = Factory(:book, :publisher => pub)
author = Factory(:author, :book => book)
author.book # => Returns book
author.book.publisher # => Returns publisher
author.publisher # => nil
So why doesn’t my through association work?
In
factory_girl/factory_girl_rails4.1.0, the following works for me:factories.rbIn the rails console:
Curiously, the last
author.publisherrequires an additional SELECT operation, whereasauthor.book.publisherdoes not (perhaps related to thenilyou observe):The same thing happens if you use
Publisher.create,Book.create,Author.createinstead ofFactoryGirl.create, so this is not factory girl behaviour but rails behaviour, something to do with howthroughassociations are cached.