我必须感到厌倦,因为我真的无法弄清楚这么简单的任务。
拥有:
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
答案 0 :(得分:3)
为什么after_save
而不是before_create
让ActiveRecord担心创建关联模型并正确分配account_id?
我没有检查过,但这应该有效:
class Account
before_create {|account| account.build_subscription(params)} # or move it to method
end