【问题标题】:Rails3 FactoryGirl has_one unknown attribute errorRails3 FactoryGirl has_one 未知属性错误
【发布时间】:2012-08-30 15:27:40
【问题描述】:

我有以下设置:

型号:

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

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 rspec factory-bot has-one


    【解决方案1】:

    您的迁移错误:belongs_to 应将外键作为 explained in doc

    【讨论】:

    • 呃,伙计,我犯了这么简单的错误,感觉很愚蠢。不过感谢您的快速回复!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多