0

我有以下设置:

楷模:

class Product < ActiveRecord::Base
  has_one :product_category

  attr_accessible :name, :product_category, :product_category_id
end

class ProductCategory < ActiveRecord::Base
  belongs_to :product

  attr_accessible :name

end

迁移:

class CreateProducts < ActiveRecord::Migration
  def change
    create_table :products do |t|
      t.references :product_category
      t.string :name

      t.timestamps
    end
  end
end

class CreateProductCategories < ActiveRecord::Migration
  def change
    create_table :product_categories do |t|
      t.string :name

      t.timestamps
    end
  end
end

现在,我想使用 FactoryGirl 和 RSpec 进行测试。所以我设置了以下 FactoryGirl 测试模型:

product_spec.rb

require 'factory_girl'
FactoryGirl.define do
  factory :product, class: Product do
    product_category {|a| a.association(:product_category)}
    name "Demo Product"
  end
end

product_category_spec.rb

require 'factory_girl'
FactoryGirl.define do
  factory :product_category, class: ProductCategory do
    name "Demo Product"
  end
end

但是当我在 product_spec.rb 上运行 RSpec 时,我收到以下错误:

can't write unknown attribute 'product_id'

我无法弄清楚为什么会发生这种情况。如果我从产品工厂中删除 product_category,一切正常。

4

1 回答 1

2

您的迁移是错误的:应该按照 docbelongs_to中的说明使用外键。

于 2012-08-30T15:30:45.477 回答