views:

169

answers:

1

I have to be dead tired because I really can't figure out such simple task as this.

Having:

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

I'm trying resolve the TODO part, or am I going about it the wrong way? Here's the test.

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
+1  A: 

Why after_save and not before_create and let ActiveRecord worry about creating associated model and assigning account_id correctly?

I haven't checked, but this should work:

class Account
  before_create {|account| account.build_subscription(params)} # or move it to method
end
MBO
It seems it doesn't work, I've tried in a callback method but didn't know about the block sent to the callback. I get the following error when testing - NoMethodError in 'Account should have a subscription at level one on creation' undefined method `level' for nil:NilClass
The Tailor
@The Tailor can you check in script/console if it works? I created new rails application and it creates dependent subscription when creating account. And check first if it really creates subscription and saves it to DB
MBO
Yes it worked in the console and I figured out that in the test i needed to ad account.save before testing the level. Thanks!
The Tailor