简体   繁体   English

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

[英]where do I define this rails method for an associated model in a mailer?

How do I define the user method in my mailer? 如何在邮件程序中定义用户方法?

I get this error: 我收到此错误:

NoMethodError in AppointmentsController#create
undefined method `user' for nil:NilClass

From this line: 从这一行:

mail to: service.user.email, subject: "Appointment Confirmation"

I have users with many services and each service can have an appointment. 我的用户有很多服务,每个服务都可以预约。

When someone makes an appointment, I want the user who owns the service for which that appoint was made to get an email. 当某人进行约会时,我希望拥有为其指定服务的用户的电子邮件。

My appointments controller looks like this: 我的约会控制器如下所示:

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 looks like this: 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

Thanks! 谢谢!

The reason is you don't pass any service to def client_confirmation . 原因是您没有将任何服务传递给def client_confirmation

You're trying to pass @service but it's not defined anywhere. 您正在尝试传递@service,但未在任何地方定义它。 You have @services defined in before action. 您在操作之前已定义@services Then you need to set @service filtering @services with some conditions you know about. 然后,您需要使用一些已知的条件来设置@service过滤@services

Assuming you have on-to-one association between Appointment and Service classes, you can change the following code of your controller. 假设AppointmentService类之间存在一对一的关联,则可以更改控制器的以下代码。

From: 从:

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

To: 至:

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

Please note that this scenario also assumes that you have one-to-many association between User and Service classes. 请注意,此方案还假定UserService类之间具有一对多关联。

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

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