Gurmukh Singh
Gurmukh Singh

Reputation: 2017

Send email in Rails Application

So I have a rails application where a recruiter posts a job (recruiter has_many jobs, all associations are set up properly) and users are able to click on a apply button which send an email using Action Mailer to the recruiter for that specific job.

User and Recruiter are two separate models created by Devise.

Jobs was generated by rails g scaffold Job .....

Heres what I have so far:

ApplyMailer.rb:

class ApplyMailer < ApplicationMailer
  def new_apply(job)
    @user = current_user
    @job = job
    mail to: @job.recruiter.email,
         subject: "Someone whats to appy for #{@job.title}"
  end
end

Jobs#show view:

<%= button_to(apply_path, class:"btn btn-info") do %>
   Apply
<% end %>

Jobs_controller.rb:

def sendemail
  @job = Job.find(params[:id])
  ApplyMailer.new_apply(@job).deliver_now
end

Routes.rb

post '/apply' => 'jobs#sendemail'

First of all I'm not sure if I'm doing this the correct way for what I'm trying to achieve. What I'm trying to do is:

So the button is on the jobs#show page, it should take that job as an argument and send an email to the associated recruiter. The current_user (User model) would be the user trying to apply for the job, so in the email view it would say the name of the user(check below).

new_apply.html.erb:

<div class="">
  <h2><%= @user.profile.name %> want to apply for the job</h2>
</div>

The question is after the button is pressed how could an email be sent to the recruiter about the job post. The email needs to contain the current_user name and email. Above is what I have tried, but no email is getting sent.

Thanks

Upvotes: 0

Views: 121

Answers (2)

Sachin
Sachin

Reputation: 353

Use Action Mailer for Sending Mail.

  class UserMailer < ApplicationMailer
  default from: '[email protected]'

  def welcome_email(user)
    @user = user
    @url  = 'http://example.com/login'
    mail(to: @user.email,
         subject: 'Welcome to My Awesome Site',
         template_path: 'notifications',
         template_name: 'another')
  end
end

For more information use this link:-

http://guides.rubyonrails.org/action_mailer_basics.html

Upvotes: 1

Oleh  Sobchuk
Oleh Sobchuk

Reputation: 3722

in your controller

def create
  # creating your job
  if @job.create
    ApplyMailer.new_apply(current_user, job).deliver_now
  else
    # what you want
  end
end

and add to mailer your user

class ApplyMailer < ApplicationMailer
  def new_apply(user, job)
    @user = user
    @job = job
    mail to: @job.recruiter.email,
         subject: "Someone whats to appy for #{@job.title}"
  end
end

BTW

you have to use routes according to CRUD according to Rails doc

Upvotes: 2

Related Questions