I have a simple model where users have one or more emails and
after_create is used to send new users a Welcome email. If I create
and save a User then after_create is triggered but there is no email
associated with the user. But the problem is that to add an Email to a
User I need to have an id for User which only happens after a save.
So is there a way to create both an Email and a User such that when
the after_create for a user is called, the user has an associated
email?
Cheers
def self.up
create_table “users”, do |t|
t.column :first_name, :string
t.column :last_name, :string
end
create_table :emails do |t|
t.column :email_address, :string
t.column :primary, :boolean
t.column :user_id, :integer
end
end
class User < ActiveRecord::Base
has_many :emails, :dependent => :destroy
end
class Email < ActiveRecord::Base
belongs_to :user
end
class UserController < ApplicationController
observer :user_observer
def signup
@user = User.new(params[:user])
@email = Email.new(params[:email])
return unless request.post?
@email.user = @user #doesn’t work since @user hasn’t been saved yet
@email.save!
@user.save!
end
end
class UserObserver < ActiveRecord::Observer
def after_create(user)
UserNotifier.deliver_welcome(user)
end
end
class UserNotifier < ActionMailer::Base
def welcome(user)
setup_email(user)
@subject = ‘Welcome’
@body[:url] = 'Welcome to our website!"
end
protected
def setup_email(user)
@recipients = “#{Email.find_by_user_id_and_primary(user, true)}”
@from = “[email protected]”
@sent_on = Time.now
@body[:user] = user
end
end