2012-08-30 86 views
0

我有以下設置:Rails3中FactoryGirl HAS_ONE未知屬性錯誤

型號:

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,則一切正常。

回答

2

您的遷移是錯誤的:belongs_to應該承擔的外鍵爲explained in doc

+0

呃,男人,我覺得啞巴已經犯了這麼簡單的錯誤。感謝您的快速回復! – Bryce