0

I have the following setup:

Models:

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

Migrations:

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

Now, I want to test that using FactoryGirl and RSpec. So I set up the following FactoryGirl test models:

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

But when I run RSpec on product_spec.rb, I get the following error:

can't write unknown attribute 'product_id'

I can't figure out why this would be happening. If I remove the product_category from the product factory, everything works.

apneadiving
  • 114,565
  • 26
  • 219
  • 213
Bryce
  • 2,802
  • 1
  • 21
  • 46

1 Answers1

2

Your migrations are wrong: belongs_to should bear the foreign key as explained in doc.

apneadiving
  • 114,565
  • 26
  • 219
  • 213
  • Ugh, man, I feel dumb having made such a simple error. Thanks for the quick reply though! – Bryce Aug 31 '12 at 01:58