简体   繁体   中英

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:

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 .

You're trying to pass @service but it's not defined anywhere. You have @services defined in before action. Then you need to set @service filtering @services with some conditions you know about.

Assuming you have on-to-one association between Appointment and Service classes, you can change the following code of your controller.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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