gpt4 book ai didi

ruby-on-rails - Factorygirl 通过模特有一个关联

转载 作者:行者123 更新时间:2023-11-28 20:32:20 24 4
gpt4 key购买 nike

我有一个模型与 has_one 关联 through 另一个模型。

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

在我的 Rails 代码中,我可以毫无问题地调用 author.publisher,因此一切正常。然而,在我的规范中(使用 Rspec 和 FactoryGirl,该关联似乎不起作用。这是我的 FactoryGirl 定义:

Factory.define :author do |a|
a.association :book
end

Factory.define :book do |b|
b.association :publisher
end

Factory.define :publisher
end

(省略了工厂的大部分属性)。

现在在我的规范中,我可以执行以下操作

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

那么,为什么我的 through 关联不起作用?

最佳答案

factory_girl/factory_girl_rails 4.1.0 中,以下对我有效:

factories.rb

FactoryGirl.define do

factory :author do
book
end

factory :book do
publisher
end

factory :publisher do
end

end

在 Rails 控制台中:

pub = FactoryGirl.create(:publisher)
#=> #<Publisher id: 1, created_at: "2013-01-30 13:35:26", updated_at: "2013-01-30 13:35:26">
book = FactoryGirl.create(:book, :publisher => pub)
#=> #<Book id: 1, publisher_id: 1, created_at: "2013-01-30 13:36:23", updated_at: "2013-01-30 13:36:23">
author = FactoryGirl.create(:author, :book => book)
#=> #<Author id: 1, book_id: 1, created_at: "2013-01-30 13:36:57", updated_at: "2013-01-30 13:36:57">
author.book
#=> #<Book id: 1, publisher_id: 1, created_at: "2013-01-30 13:36:23", updated_at: "2013-01-30 13:36:23">
author.book.publisher
#=> #<Publisher id: 1, created_at: "2013-01-30 13:35:26", updated_at: "2013-01-30 13:35:26">
author.publisher
#=> #<Publisher id: 1, created_at: "2013-01-30 13:35:26", updated_at: "2013-01-30 13:35:26">

奇怪的是,最后一个 author.publisher 需要额外的 SELECT 操作,而 author.book.publisher 不需要(可能与 nil 你观察到):

Publisher Load (0.2ms)  SELECT "publishers".* FROM "publishers"
INNER JOIN "books" ON "publishers"."id" = "books"."publisher_id"
WHERE "books"."id" = 1 LIMIT 1

如果您使用 Publisher.createBook.createAuthor.create 而不是 FactoryGirl.create,也会发生同样的事情,所以这不是 factory girl 的行为,而是 rails 的行为,与 through 关联的缓存方式有关。

关于ruby-on-rails - Factorygirl 通过模特有一个关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14604505/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com