app/controllers/users_controller.rb
class UsersController < ApplicationController
def create
@user = User.new(user_params)
if @user.save
UserMailer.activation(@user).deliver_later
redirect_to root_url
else
render "new"
end
end
end
app/mailers/user_mailer.rb
class UserMailer < ApplicationMailer
def activation(user)
@user = user
mail(to: @user.email, subject: 'Please activate your account')
end
end
app/views/user_mailer/activation.html.slim
p= "Hello,#{@user.name}Mr."
Click the p link to activate your account
= link_to "Activate account", edit_account_activation_url(@user.activation_token, email: @user.email)
create
app/models/user.rb
class User < ApplicationRecord
attr_accessor :activation_token
before_create :create_activation_digest
private
def create_activation_digest
self.activation_token = SecureRandom.urlsafe_base64
self.activation_digest = BCrypt::Password.create(activation_token)
end
end
ActionView::Template::Error (No route matches {:action=>"edit", :controller=>"account_activations", :email=>"address", :id=>nil}, possible unmatched constraints: [:id]):
@ user.activation_token
has become nil
@ user.object_id
and @ user.activation_token
44860
"I2BCoTsomoNhqNF0q_zRKw"
[ActiveJob] -----
User Load (0.8ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2 [["id", 70], ["LIMIT", 1]]
[ActiveJob] -----
44980
nil
It's a different object and ʻactivation_token is also
nil`!
deliver_later
If you send an email with deliver_later
, you will see that it is looking for a user from the database before running ʻUserMailer`.
User Load (0.8ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2 [["id", 70], ["LIMIT", 1]]
The value of the ʻactivation_token attribute cannot be referenced in the ʻuser
object obtained from the database after saving because it only has the @ user
when @ user.save
is executed.
deliver_now
app/controllers/users_controller.rb
class UsersController < ApplicationController
def create
@user = User.new(user_params)
if @user.save
UserMailer.activation(@user).deliver_now
redirect_to root_url
else
render "new"
end
end
end
If you send with deliver_now
, the argument will be passed as it is, so it succeeds!
37900
"2kQLrYZjinTiJFKE3jdPqQ"
37900
"2kQLrYZjinTiJFKE3jdPqQ"
deliver_now
and deliver_later
deliver_now
Send an email immediately
deliver_late
ʻSend an email later using Active Job`
https://railsguides.jp/active_job_basics.html#action-mailer
https://api.rubyonrails.org/classes/ActionMailer/MessageDelivery.html#method-i-deliver_later
Recommended Posts