2010-02-24 111 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