繁体   English   中英

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

[英]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

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

从:

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

至:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM