2012-06-18 80 views
2

我正在嘗試爲我正在開發的Rails應用程序構建基本購物車。has_one關聯和工廠女孩的任意屬性錯誤

沒什麼特別的,
- 購物車中有許多line_items
- 相關聯的每個LINE_ITEM HAS_ONE產品與它

class Cart < ActiveRecord::Base 
    attr_accessible :line_items 
    has_many :line_items, :dependent => :destroy 
end 

class LineItem < ActiveRecord::Base 
    attr_accessible :quantity, :product 

    belongs_to :cart 
    has_one :product 
end 

我試圖使用RSpec的測試此關聯的量,但我做錯了,因爲我得到一個錯誤,說:DEPRECATION WARNING: You're trying to create an attribute 'line_item_id'. Writing arbitrary attributes on a model is deprecated,我不知道爲什麼。

在我factories.rb文件,我定義LINE_ITEM工廠如下:

factory :line_item do 
    quantity { Random.rand(1..5) } 
    product 
end 

factory :cart do 
    factory :cart_with_two_line_items do 
    ignore do 
     line_item_count 2 
    end 

    after(:create) do |cart, evaluator| 
     FactoryGirl.create_list(:line_item, evaluator.line_item_count, cart_id: cart) # < 104 
    end 
    end 
end 

任何指針,我要去哪裏錯了,它可能是一些基本的東西,但我仍然很新的Rspec的。提前致謝。

編輯:line_item_spec.rb

require 'spec_helper' 

describe LineItem do 
before do 
    @line_item = FactoryGirl.create(:line_item) 
end 

回答

3

也許你忘了申報的產品型號的關聯。

class Product < Activerecord::Base 
    belongs_to :line_item 

belongs_to會期望您的產品表具有一列:line_item_id。你是否運行遷移並修改模型?

+0

是的,我認爲就是這樣!我多麼愚蠢。這可能是一個愚蠢的問題,但爲了幫助我理解 - 因爲我通常只在視圖和控制器層中工作,所以模型對我來說還是比較新的 - 爲什麼在產品模型中需要對應模型?對於協會來說,情況總是如此,或者在某種情況下它是單向的嗎? – purpletonic

+0

......嗯,事實並非如此。因爲我仍然收到通知: '退化警告:您正嘗試創建屬性'line_item_id'。在模型上編寫任意屬性已被棄用。請使用'attr_writer'等(在中的塊(4級)調用/code/spec/factories.rb:104)' – purpletonic

+0

此文件中的行104有什麼代碼?請粘貼相關的代碼,並附上一些註釋,指示104行。 – Salil