我在哪里为邮件中的关联模型定义此rails方法?

时间:2014-09-09 18:30:26

标签: ruby-on-rails actionmailer

如何在邮件程序中定义用户方法?

我收到此错误:

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

谢谢!

2 个答案:

答案 0 :(得分:0)

原因是您没有将任何服务传递给 def client_confirmation

您尝试传递 @service ,但未在任何地方定义。您在操作前定义了 @services 。然后,您需要根据您了解的某些条件设置 @service 过滤 @services

答案 1 :(得分:0)

假设您在AppointmentService类之间存在一对一关联,则可以更改控制器的以下代码。

自:

ClientMailer.client_confirmation(@appointment, @service, @user).deliver

要:

ClientMailer.client_confirmation(@appointment, @appointment.service, @user).deliver

请注意,此方案还假定您在UserService类之间存在一对多关联。