[英]where do I define this rails method for an associated model in a mailer?
如何在郵件程序中定義用戶方法?
我收到此錯誤:
NoMethodError in AppointmentsController#create
undefined method `user' for nil:NilClass
從這一行:
mail to: service.user.email, subject: "Appointment Confirmation"
我的用戶有很多服務,每個服務都可以預約。
當某人進行約會時,我希望擁有為其指定服務的用戶的電子郵件。
我的約會控制器如下所示:
before_action :load_services, only: [:new, :edit, :create, :update]
def create
@appointment = Appointment.new(appointment_params)
respond_to do |format|
if @appointment.save
ClientMailer.client_confirmation(@appointment, @service, @user).deliver
format.html { redirect_to @appointment, notice: 'Appointment was successfully created.' }
format.json { render :show, status: :created, location: @appointment }
else
format.html { render :new }
format.json { render json: @appointment.errors, status: :unprocessable_entity }
end
end
end
def load_services
@services = Service.all.collect {|service| [ service.title, service.id] }
end
client_mailer.rb
看起來像這樣:
class ClientMailer < ActionMailer::Base
default from: "bookme@example.com"
def client_confirmation(appointment, service, user)
@appointment = appointment
@service = service
@user = user
@greeting = "Hi"
mail to: service.user.email, subject: "Appointment Confirmation"
end
end
謝謝!
原因是您沒有將任何服務傳遞給def client_confirmation 。
您正在嘗試傳遞@service,但未在任何地方定義它。 您在操作之前已定義@services 。 然后,您需要使用一些已知的條件來設置@service過濾@services 。
假設Appointment
和Service
類之間存在一對一的關聯,則可以更改控制器的以下代碼。
從:
ClientMailer.client_confirmation(@appointment, @service, @user).deliver
至:
ClientMailer.client_confirmation(@appointment, @appointment.service, @user).deliver
請注意,此方案還假定User
和Service
類之間具有一對多關聯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.