0

在控制台中我这样做:

board = FactoryGirl.build(:board_with_source)

board.sources
=> [#<Board id: 6, name: "Free Ruby Books", description: "Ruby Books - Free and Paid ones", created_at: "2013-06-21 12:21:34", updated_at: "2013-06-21 12:21:34", user_id: nil>]

board.sources.count
=> 0 

为什么它显示 0 ?

FactoryGirl 设置:

# Read about factories at https://github.com/thoughtbot/factory_girl

FactoryGirl.define do
  factory :board do
    name "Ruby Books"
    description "Ruby Books - Free and Paid ones"
  end

  factory :board_with_source, parent: :board do
    after :build do |board|
      board.sources << FactoryGirl.create(:board, name: "Free Ruby Books")
    end
  end
end
4

1 回答 1

4

因为你使用build了,它只在内存中构建一个对象,而不是在数据库中持久化。

count方法将 db 查询为“SELECT COUNT(*)....”。所以你的计数为零。

添加

要在控制台中显示计数,您可以使用size方法

s1 = @board.sources.new(attr)
s1.save!
@board.sources.count
# => 1
@board.sources.size
# => 1

s2 = @board.sources.new(attr)
@board.sources.count
# => 1
@board.sources.size
# => 2
于 2013-06-21T12:50:35.860 回答