I am new to Rails and I am faced with a problem: I have to build an app for a Coworking Area. Freelancers complete a form and they can have one of these two statuses: accept or confirm. I handle this with Enum type. I can get their mails: Freelancer.confirm.map{ |freelancer| freelancer.email }
In Rails console:
Freelancer Load (2.8ms) SELECT "freelancers".* FROM "freelancers" WHERE "freelancers"."status" = ? [["status", 0]] => ["[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]"]
But I can't use it correctly in my app:
In my app/models/freelancer.rb
class Freelancer < ApplicationRecord
enum status: [:confirm, :accept]
def send_contract_email
UserMailer.contract_email(self).deliver_now
end
end
In app/mailers/user_mailer.rb
class UserMailer < ApplicationMailer
def contract_email(freelancers)
@emails = freelancers.accept.map{|freelancer| freelancer.email}
mail(to: @emails, subject: 'Welcome to my site')
end
end
In lib/tasks/email_tasks.rake
desc 'send contract email'
task send_contract_email: :environment do
UserMailer.contract_email(freelancers).deliver_now
end
In config/environments/schedule.rb (set to 5 minutes for more convenience)
every '5 * * * *' do
rake 'send_contract_email'
end
And in app/views/user_mailer/contract_email.html.erb
<!DOCTYPE html>
<html>
<head>
<meta content='text/html; charset=UTF-8' http-equiv='Content-Type' />
</head>
<body>
<h1>Hi!</h1>
</body>
</html>
When I run rake send_contract_email for testing everything works and checking whether the email is sent or not, it displays an error:
rake aborted! NameError: undefined local variable or method
freelancers' for main:Object /home/gaelle/Bureau/corworking/coworking/lib/tasks/email_tasks.rake:3:in
block in ' /home/gaelle/.rvm/gems/ruby-2.4.1/gems/rake-12.1.0/exe/rake:27:in<top (required)>' /home/gaelle/.rvm/gems/ruby-2.4.1/bin/ruby_executable_hooks:15:in
eval' /home/gaelle/.rvm/gems/ruby-2.4.1/bin/ruby_executable_hooks:15:in `' Tasks: TOP => send_contract_email (See full trace by running task with --trace)
The problem seems to be in UserMailer but I can not understand why I am wrong because I use Freelancer (with self) in the model. Thanks for your help!
It looks like in your task, send_contract_email
, you're using a local variable freelancers
that hasn't been initialized. You'll need to set freelancers
to be a list of freelancers in the task before calling UserMailer.contract_email
, or else pass the list into the task as a parameter. Here's a nice post with information about how to pass parameters to rake tasks.