質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Ruby on Rails 5

Ruby on Rails 5は、オープンソースのWebアプリケーションフレームワークです。「同じことを繰り返さない」というRailsの基本理念のもと、他のフレームワークより少ないコードで簡単に開発できるよう設計されています。

Q&A

解決済

1回答

686閲覧

rails チュートリアル11章 メールでの有効化で、メールをクリックしてきたユーザーのアドレスがとれない。

tori315

総合スコア21

Ruby on Rails 5

Ruby on Rails 5は、オープンソースのWebアプリケーションフレームワークです。「同じことを繰り返さない」というRailsの基本理念のもと、他のフレームワークより少ないコードで簡単に開発できるよう設計されています。

0グッド

1クリップ

投稿2020/01/18 04:12

rails チュートリアル11章のところを参考にメールでユーザーの有効化をする処理で、メールは送れるのですが、URLをクリックしてきたユーザーのアドレスが取れていないようで、有効化ができません。どなたかお知恵を貸してください。

ruby

1def create 2 @user = User.new(user_params) 3 @user.imagename = "default_user.jpg" 4 @user.point = 0 5 @user.finishcount = 0 6 password = params[:password] 7 password_confirmation = params[:password_confirmation] 8 @user.save 9 if @user.save 10 session[:user_id] = @user.id 11 @user.send_activation_email                 #メールを送る 12 flash[:notice] = "メールを確認して登録を完了してください。" 13 redirect_to("/") 14 else 15 if User.find_by(email:params[:email]) 16 @error_message = "そのEmailアドレスは使われています" 17 else 18 if password.length < 6 19 @error_message = "パスワードは6字以上です" 20 elsif password.length > 18 21 @error_message = "パスワードは18字以下です" 22 elsif password != password_confirmation 23 @error_message = "パスワードと確認パスワードが一致しません" 24 else 25 @error_message = "入力されたEmailは正しくありません" 26 end 27 end 28 render("/users/new") 29 end 30 end

ruby

1class User < ApplicationRecord 2 attr_accessor :remember_token , :activation_token # 記憶トークンと有効化トークンを定義 3 before_create :create_activation_digest # 作成前に適用 4 5 6def self.search(search) 7 if search 8 User.where(['user_name LIKE?',"%#{search}%"]) 9 else 10 User.all 11 end 12end 13 14def send_activation_email 15 UserMailer.account_activation(self).deliver_now 16end 17 18def activate 19 update_attribute(:activated, true) 20 update_attribute(:activated_at, Time.zone.now) 21end 22 23def remember 24 self.remember_token = User.new_token 25 update_attribute(:remember_digest, User.digest(remember_token)) 26end 27 28# 渡された文字列のハッシュ値を返す 29def User.digest(string) 30cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST : 31 BCrypt::Engine.cost 32BCrypt::Password.create(string, cost: cost) 33end 34 35# ランダムなトークンを返す 36def User.new_token 37 SecureRandom.urlsafe_base64 38end 39 40 41# 渡されたトークンがダイジェストと一致したらtrueを返す 42def authenticated?(attritubte, token) 43 digest = send("#{attritubte}_digest") 44 return false if digest.nil? 45 BCrypt::Password.new(digest).is_password?(token) 46end 47 48# ユーザーのログイン情報を破棄する 49def forget 50 update_attribute(:remember_digest, nil) 51end 52 53 54 55# 有効化トークンとダイジェストを作成および代入する 56def create_activation_digest 57 self.activation_token = User.new_token # ハッシュ化した記憶トークンを有効化トークン属性に代入 58 self.activation_digest = User.digest(activation_token) # 有効化トークンをBcryptで暗号化し、有効化ダイジェスト属性に代入 59end 60 61end 62

ruby

1class UserMailer < ApplicationMailer 2 default from: 'toriyama.muct@gmail.com' 3 4 5 def account_activation(user) 6 @user = user 7 mail to: user.email, subject: "Welcome" #subjectは件名 8 end 9 10 def password_reset 11 @greeting = "Hi" 12 13 mail to: "to@example.org" 14 end 15 16 17end 18

ruby

1<p>hello. <%= @user.user_name %>,</p> 2 3<p> 4 Welcome NEET'S RIDE &nbsp;Plese&nbsp;&nbsp;click: 5</p> 6 7<%= link_to "Activate", edit_account_activation_url(@user.activation_token, email: @user.email ) %>

ruby

1class AccountActivationsController < ApplicationController 2 def edit 3 user = User.find_by(email: params[:email]) 4 if user && !user.activated? && user.authenticated?(:activation, params[:id]) 5 user.update_attribute(:activated, true) 6 user.update_attribute(:activated_at, Time.zone.now) 7 log_in user 8 flash[:notice] = "アカウントを有効にしました。ログインしてください。" 9 redirect_to("/") 10 else 11 flash[:notice] = "アカウントを有効にできませんでした。" 12 @user = user #消す 13 redirect_to("/") 14 end 15 end 16end

URLをクリックすると、ここのコントローラにはくるのですが、userがnilになっているようです。処理はいつも、elseの方で処理されます。

log

1actionpack (5.2.4.1) lib/action_dispatch/middleware/debug_exceptions.rb:65:in `call' 2web-console (3.7.0) lib/web_console/middleware.rb:135:in `call_app' 3web-console (3.7.0) lib/web_console/middleware.rb:30:in `block in call' 4web-console (3.7.0) lib/web_console/middleware.rb:20:in `catch' 5web-console (3.7.0) lib/web_console/middleware.rb:20:in `call' 6actionpack (5.2.4.1) lib/action_dispatch/middleware/show_exceptions.rb:33:in `call' 7railties (5.2.4.1) lib/rails/rack/logger.rb:38:in `call_app' 8railties (5.2.4.1) lib/rails/rack/logger.rb:26:in `block in call' 9activesupport (5.2.4.1) lib/active_support/tagged_logging.rb:71:in `block in tagged' 10activesupport (5.2.4.1) lib/active_support/tagged_logging.rb:28:in `tagged' 11activesupport (5.2.4.1) lib/active_support/tagged_logging.rb:71:in `tagged' 12railties (5.2.4.1) lib/rails/rack/logger.rb:26:in `call' 13sprockets-rails (3.2.1) lib/sprockets/rails/quiet_assets.rb:13:in `call' 14actionpack (5.2.4.1) lib/action_dispatch/middleware/remote_ip.rb:81:in `call' 15actionpack (5.2.4.1) lib/action_dispatch/middleware/request_id.rb:27:in `call' 16rack (2.0.8) lib/rack/method_override.rb:22:in `call' 17rack (2.0.8) lib/rack/runtime.rb:22:in `call' 18activesupport (5.2.4.1) lib/active_support/cache/strategy/local_cache_middleware.rb:29:in `call' 19actionpack (5.2.4.1) lib/action_dispatch/middleware/executor.rb:14:in `call' 20actionpack (5.2.4.1) lib/action_dispatch/middleware/static.rb:127:in `call' 21rack (2.0.8) lib/rack/sendfile.rb:111:in `call' 22railties (5.2.4.1) lib/rails/engine.rb:524:in `call' 23puma (3.12.2) lib/puma/configuration.rb:227:in `call' 24puma (3.12.2) lib/puma/server.rb:674:in `handle_request' 25puma (3.12.2) lib/puma/server.rb:476:in `process_client' 26puma (3.12.2) lib/puma/server.rb:334:in `block in run' 27puma (3.12.2) lib/puma/thread_pool.rb:135:in `block in spawn_thread' 28Started POST "/users/create" for ::1 at 2020-01-18 12:37:36 +0900 29Processing by UsersController#create as HTML 30 Parameters: {"utf8"=>"✓", "authenticity_token"=>"o9yKp5OUFDMyB2eQpVSpChIF3TWUcnbqShRgukbzCfALnfqsipePghb1d2BOjPATPgW5pXJ6mvBptS/2CC77fA==", "user_name"=>"田中", "email"=>"sample@co.jp", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"} 31Unpermitted parameters: :utf8, :authenticity_token 32  (0.1ms) begin transaction 33 ↳ app/controllers/users_controller.rb:19 34 User Exists (0.7ms) SELECT 1 AS one FROM "users" WHERE "users"."email" = ? LIMIT ? [["email", "sample@co.jp"], ["LIMIT", 1]] 35 ↳ app/controllers/users_controller.rb:19 36 User Create (3.0ms) INSERT INTO "users" ("user_name", "password_digest", "email", "imagename", "finishcount", "point", "created_at", "updated_at", "activation_digest") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) [["user_name", "田中"], ["password_digest", "$2a$12$Y1ht9BMlEn373nv.mFr7Tus0HRS05YpnPXXFV8ighpMvfvJenTNGm"], ["email", "sample@co.jp"], ["imagename", "default_user.jpg"], ["finishcount", 0], ["point", 0.0], ["created_at", "2020-01-18 12:37:37.618435"], ["updated_at", "2020-01-18 12:37:37.618435"], ["activation_digest", "$2a$12$dB4cuZG6hYCCZPDHR7.8veJ92pE6KaGFtvqTgGe8g7POZ4.2K6VMC"]] 37 ↳ app/controllers/users_controller.rb:19 38  (145.2ms) commit transaction 39 ↳ app/controllers/users_controller.rb:19 40  (0.1ms) begin transaction 41 ↳ app/controllers/users_controller.rb:20 42 User Exists (0.5ms) SELECT 1 AS one FROM "users" WHERE "users"."email" = ? AND "users"."id" != ? LIMIT ? [["email", "sample@co.jp"], ["id", 38], ["LIMIT", 1]] 43 ↳ app/controllers/users_controller.rb:20 44  (0.1ms) commit transaction 45 ↳ app/controllers/users_controller.rb:20 46 Rendering user_mailer/account_activation.html.erb within layouts/mailer 47 Rendered user_mailer/account_activation.html.erb within layouts/mailer (1.5ms) 48 Rendering user_mailer/account_activation.text.erb within layouts/mailer 49 Rendered user_mailer/account_activation.text.erb within layouts/mailer (1.2ms) 50UserMailer#account_activation: processed outbound mail in 52.8ms 51Sent mail to sample@co.jp (138.9ms) 52Date: Sat, 18 Jan 2020 12:37:38 +0900 53From: toriyama.muct@gmail.com 54To: sample@co.jp 55Message-ID: <5e227d825f7dd_7ac45b526c84451@LS150-PC.mail> 56Subject: Welcome NEET'S RIDE 57Mime-Version: 1.0 58Content-Type: multipart/alternative; 59 boundary="--==_mimepart_5e227d825e66a_7ac45b526c84326"; 60 charset=UTF-8 61Content-Transfer-Encoding: 7bit 62 63 64----==_mimepart_5e227d825e66a_7ac45b526c84326 65Content-Type: text/plain; 66 charset=UTF-8 67Content-Transfer-Encoding: quoted-printable 68 69 =E7=94=B0=E4=B8=AD,=0D 70Welcome NEET'S RIDE &nbsp;Plese&nbsp;&nbsp;click:=0D 71http://localhost:3000/account_activations/0TUelYOMvg6C4resAWAzjg/edit?ema= 72il=3Dsample%40co.jp=0D 73=0D 74 75----==_mimepart_5e227d825e66a_7ac45b526c84326 76Content-Type: text/html; 77 charset=UTF-8 78Content-Transfer-Encoding: quoted-printable 79 80<!DOCTYPE html>=0D 81<html>=0D 82 <head>=0D 83 <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3Dutf= 84-8" />=0D 85 <style>=0D 86 /* Email styles need to be inline */=0D 87 </style>=0D 88 </head>=0D 89=0D 90 <body>=0D 91 <p>hello. =E7=94=B0=E4=B8=AD,</p>=0D 92=0D 93<p>=0D 94 Welcome NEET'S RIDE &nbsp;Plese&nbsp;&nbsp;click:=0D 95</p>=0D 96=0D 97<a href=3D"http://localhost:3000/account_activations/0TUelYOMvg6C4resAWAz= 98jg/edit?%E3%80%80email=3Dsample%40co.jp">Activate</a>=0D 99 </body>=0D 100</html>=0D 101

logでは、アドレスが送られているのようなのに、params[:email]で取れないのはなぜなのでしょうか。どうぞよろしくお願いします。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

winterboum

2020/01/18 13:27

logはメール送信までで、AccountActivationsController#editへのアクセス部分がないですが。
tori315

2020/01/18 13:59

質問の方に追加すると、文字数制限で投稿できないので、こちらに書かせていただきます。 以下、返ってきたときのログです。質問のアドレスとは違いますが、これでいいでしょうか? Started GET "/letter_opener/1579354887_2057996_ad689a3/rich" for ::1 at 2020-01-18 22:42:50 +0900 Processing by LetterOpenerWeb::LettersController#show as HTML Parameters: {"id"=>"1579354887_2057996_ad689a3", "style"=>"rich"} Rendering html template Rendered html template (0.1ms) Completed 200 OK in 1058ms (Views: 75.2ms | ActiveRecord: 0.0ms) Started GET "/account_activations/CXb0oS2Zuhe-FNYT2Wf6GA/edit?%E3%80%80email=sample1%40co.jp" for ::1 at 2020-01-18 22:42:59 +0900 Processing by AccountActivationsController#edit as HTML Parameters: {" email"=>"sample1@co.jp", "id"=>"CXb0oS2Zuhe-FNYT2Wf6GA"} User Load (20.4ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ? [["id", 40], ["LIMIT", 1]] ↳ app/controllers/application_controller.rb:7 User Load (1.2ms) SELECT "users".* FROM "users" WHERE "users"."email" IS NULL LIMIT ? [["LIMIT", 1]] ↳ app/controllers/account_activations_controller.rb:3 Redirected to http://localhost:3000/ Completed 302 Found in 329ms (ActiveRecord: 21.6ms) Started GET "/" for ::1 at 2020-01-18 22:43:05 +0900 Processing by HomeController#top as HTML User Load (0.4ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ? [["id", 40], ["LIMIT", 1]] ↳ app/controllers/application_controller.rb:7 Rendering home/top.html.erb within layouts/application Rendered home/top.html.erb within layouts/application (1.2ms) Completed 200 OK in 1767ms (Views: 1726.3ms | ActiveRecord: 0.4ms)
tori315

2020/01/18 14:07

↳ app/controllers/application_controller.rb:7のところは、 class ApplicationController < ActionController::Base include SessionsHelper before_action :set_current_user def set_current_user if (user_id = session[:user_id]) @current_user ||= User.find_by(id: user_id)   #ここが7行目です。 elsif (user_id = cookies.signed[:user_id]) user = User.find_by(id: user_id) if user && user.authenticated?(:remember, cookies[:remember_token]) log_in @user @current_user = user end end end ここが原因になるのでしょうか?
guest

回答1

0

ベストアンサー

メールアドレスの前に全角空白が入っているのが原因ですね。
ざっと見た所なぜ入るか読み込めていません。
明日見なおしてみますが、その目(どこで空白がはいるんだ!)で見なおしてみてください

投稿2020/01/18 14:29

winterboum

総合スコア23333

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

tori315

2020/01/18 14:39

ありがとうございます。考えてみます。
tori315

2020/01/18 15:03

<%= link_to "Activate", edit_account_activation_url(@user.activation_token, email: @user.email ) %> <%= link_to"Activate",edit_account_activation_url(@user.activation_token,email:@user.email) %> 詰めてみたら、いけました。ご指摘があったおかげです。ありがとうございました。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問