我有下面的方法将数据保存到 users 表以及 user_details 表。
当我将 @newUser 变量传递给 EmailMailer 时,我无法访问 user_details 属性。如何在 @newUser 对象中传递 user_details 而无需重新查询数据库?
楷模
class User < ActiveRecord::Base
has_one :user_details, :dependent => :destroy
accepts_nested_attributes_for :user_details
attr_accessible :email, :password, :password_confirmation, :remember_me, :username, :login, :home_phone, :cell_phone, :work_phone, :birthday, :home_address, :work_address, :position, :company, :user_details_attributes
end
class UserDetails < ActiveRecord::Base
belongs_to :user
attr_accessible :first_name, :last_name, :home_phone, :cell_phone, :work_phone, :birthday, :home_address, :work_address, :position, :company
end
控制器
# POST /users
def create
@newUser = User.new(params[:user], :include =>:user_details)
# create password
require 'securerandom'
password = SecureRandom.urlsafe_base64(8)
@newUser.password = password
respond_to do |format|
if @newUser.save
@newUser.build_user_details
# Tell the UserMailer to send a welcome Email after save
EmailMailer.welcome_email(@newUser).deliver
# To be used in dev only. Just tests if the email was queued for sending.
#assert ActionMailer::Base.deliveries.empty?
format.html {
flash[:success] = "User created successfully"
redirect_to(contacts_path)
}
else
format.html {
flash[:error] = flash[:error].to_a.concat resource.errors.full_messages
redirect_to(contacts_path)
}
end
end
end