Antony Sastre
Antony Sastre

Reputation: 617

Creating associated models on create in Rails?

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

Upvotes: 2

Views: 3778

Answers (1)

MBO
MBO

Reputation: 30985

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

Upvotes: 3

Related Questions