2010-02-24 115 views
2

我得累死了,因爲我真的無法弄清楚這樣簡單的任務。在Rails中創建相關模型?

有:

class Account < ActiveRecord::Base 
    has_one :subscription, :dependent => :destroy 

    after_save :append_subscription 

    private 
    def append_subscription 
    # TODO 
    end 
end 

# Subscription(id: integer, account_id: integer, level: integer (: 1), starts_at: date, ends_at:date, created_at: datetime, updated_at: datetime) 

class Subscription < ActiveRecord::Base 
    belongs_to :account 
end 

我試圖解決的TODO部分,或者我要對錯誤的方式?這是測試。

describe Account do 
    include AccountSpecHelper 

    it "should have a subscription at least at level one on creation" do 
    account = Account.create 
    account.subscription.level.should be(1) 
    end 
end 

回答

3

爲什麼after_save而不是before_create,讓ActiveRecord的擔心創建關聯的模型和正確分配ACCOUNT_ID?

我沒有檢查,但這應該工作:

class Account 
    before_create {|account| account.build_subscription(params)} # or move it to method 
end 
+0

看來它不工作,我想在一個回調方法,但不知道送到回調塊。測試時出現以下錯誤 - '帳戶中的NoMethodError在創建時應具有一級訂閱'未定義的方法'級別'爲零:NilClass – 2010-02-24 12:48:44

+1

@The裁縫可以檢查腳本/控制檯是否可用?我創建了新的rails應用程序,並在創建帳戶時創建相關訂閱。首先檢查是否確實創建了訂閱並將其保存到數據庫 – MBO 2010-02-24 12:59:30

+0

是的,它在控制檯中工作,我發現在測試之前我需要測試廣告帳戶。謝謝! – 2010-02-24 13:16:46