我有下面的方法將數據保存到用戶表以及user_details表。Rails如何獲得關聯的模型屬性
當我將@ 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
@newuser是一個實例變量,您可以像處理視圖一樣使用實例變量來處理郵件,就像在視圖中一樣。 – Ryan
我知道瑞安,但我不知道如何獲得@ newUser實例變量可訪問的user_details。 – Catfish
@Catfish僅供參考,你不應該像這樣發送內聯郵件。他們應該被轉移到後臺處理。您可以使用DelayedJob或Resque輕鬆完成此操作。這樣的內聯電子郵件傳遞將對您的表現產生嚴重影響。 –