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

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

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

Rubyはプログラミング言語のひとつで、オープンソース、オブジェクト指向のプログラミング開発に対応しています。

Ruby on Rails

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

Q&A

解決済

1回答

1494閲覧

[rails チュートリアル] undefined method `[]' for nil:NilClass

Maaxuhbd

総合スコア7

Ruby

Rubyはプログラミング言語のひとつで、オープンソース、オブジェクト指向のプログラミング開発に対応しています。

Ruby on Rails

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

0グッド

0クリップ

投稿2021/08/02 07:24

編集2021/08/03 04:18

railsチュートリアルの8章を行っていた時に下記のようなエラーが発生しました。
イメージ説明
おそらく、sessionメソッドが原因だと思われるので関連しそうなファイルを載せておきます

session_controller

ruby

1 def create 2 user = User.find_by(email: params[:session][:email].downcase) 3 if user && user.authenticate(params[:session][:password]) 4 # ユーザーログイン後にユーザー情報のページにリダイレクトする 5 else 6 # エラーメッセージを作成する 7 render 'new' 8 end 9 end

user.rb

ruby

1lass User < ApplicationRecord 2 before_save { self.email = email.downcase } 3 validates :name, presence: true, length: { maximum: 50 } 4 VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+.[a-z]+\z/i 5 validates :email, presence: true, length: { maximum: 255 },format: { with: VALID_EMAIL_REGEX },uniqueness: { case_sensitive: false } 6 validates :password, presence: true, length: { minimum: 6 } 7 has_secure_password 8end

gemfile

ruby

1source 'https://rubygems.org' 2git_source(:github) { |repo| "https://github.com/#{repo}.git" } 3 4ruby '2.6.3' 5 6# Bundle edge Rails instead: gem 'rails', github: 'rails/rails', branch: 'main' 7gem 'rails', '~> 6.1.3', '>= 6.1.3.2' 8# Use sqlite3 as the database for Active Record 9gem 'sqlite3', '~> 1.4' 10# Use Puma as the app server 11gem 'puma', '~> 5.0' 12# Use SCSS for stylesheets 13gem 'sass-rails', '>= 6' 14# Transpile app-like JavaScript. Read more: https://github.com/rails/webpacker 15gem 'webpacker', '~> 5.0' 16# Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks 17gem 'turbolinks', '~> 5' 18# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder 19gem 'jbuilder', '~> 2.7' 20# Use Redis adapter to run Action Cable in production 21# gem 'redis', '~> 4.0' 22# Use Active Model has_secure_password 23# gem 'bcrypt', '~> 3.1.7' 24 25# Use Active Storage variant 26# gem 'image_processing', '~> 1.2' 27 28# Reduces boot times through caching; required in config/boot.rb 29gem 'bootsnap', '>= 1.4.4', require: false 30 31group :development, :test do 32 # Call 'byebug' anywhere in the code to stop execution and get a debugger console 33 gem 'byebug', platforms: [:mri, :mingw, :x64_mingw] 34end 35 36group :development do 37 # Access an interactive console on exception pages or by calling 'console' anywhere in the code. 38 gem 'web-console', '>= 4.1.0' 39 # Display performance information such as SQL time and flame graphs for each request in your browser. 40 # Can be configured to work on production as well see: https://github.com/MiniProfiler/rack-mini-profiler/blob/master/README.md 41 gem 'rack-mini-profiler', '~> 2.0' 42 gem 'listen', '~> 3.3' 43 # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring 44 gem 'spring' 45end 46 47group :test do 48 # Adds support for Capybara system testing and selenium driver 49 gem 'capybara', '>= 3.26' 50 gem 'selenium-webdriver' 51 # Easy installation and use of web drivers to run system tests with browsers 52 gem 'webdrivers' 53end 54 55# Windows does not include zoneinfo files, so bundle the tzinfo-data gem 56gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby] 57 58gem 'bootstrap-sass', '3.3.7' 59 60gem 'rails-controller-testing' 61gem 'bcrypt', '3.1.12'

sessions/new.html.erb

ruby

1<% provide(:title, "Log in") %> 2<h1>Log in</h1> 3 4<div class="row"> 5 <div class="col-md-6 col-md-offset-3"> 6 <%= form_with url: login_path do |f| %> 7 8 <%= f.label :email %> 9 <%= f.email_field :email, class: 'form-control' %> 10 11 <%= f.label :password %> 12 <%= f.password_field :password, class: 'form-control' %> 13 14 <%= f.submit "Log in", class: "btn btn-primary" %> 15 <% end %> 16 17 <p>New user? <%= link_to "Sign up now!", signup_path %></p> 18 </div> 19</div>

Railsチュートリアルの教材と変更した点は、form_for→form_with

paramsメソッドは、sessions_controllerには記載していません。
__users_controller__で記載している

ruby

1class UsersController < ApplicationController 2 3 def show 4 #(params[:id])にユーザーidの1が入る 5 @user = User.find(params[:id]) 6 end 7 8 def new 9 #空のオブジェクト作成 10 @user = User.new 11 end 12 13 def create 14 @user = User.new(user_params) 15 if @user.save 16 log_in @user 17 flash[:success] = "Welcome to the Sample App!" 18 redirect_to @user 19 else 20 render 'new' 21 end 22 end 23 24 private 25 26 def user_params 27 params.require(:user).permit(:name,:email,:password,:password_confirmaiton) 28 end 29end

paramsの中身をdebuggerで検証。

2, 11] in /Users/nishiwakidaiki/Desktop/sample_app/app/controllers/sessions_controller.rb 2: def new 3: end 4: 5: def create 6: debugger => 7: user = User.find_by(email: params[:session][:email].downcase) 8: if user && user.authenticate(params[:session][:password]) 9: # ユーザーログイン後にユーザー情報のページにリダイレクトする 10: log_in user 11: redirect_to user (byebug) params #<ActionController::Parameters {"authenticity_token"=>"fMkUiCsYcuYyMSedk1n9yPrEvvqLVx4Fgsp36NCLrLl8Ie3_LFZLKzY-Q-i3VqV8BD0bfjVGe4VnuUv7JAMhzw", "email"=>"", "password"=>"", "commit"=>"Log in", "controller"=>"sessions", "action"=>"create"} permitted: false>

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

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

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

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

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

winterboum

2021/08/02 11:22

LOGINのviewを載せてください Params がどうであったか確認したいのですが。添付画面の欄外下の方にないかな。もしくは logから読み出す
guest

回答1

0

ベストアンサー

params[:session][:email] としていますが、Paramsみると
Parameters {"authenticity_token"=>"fMkUiCMhzw", "email"=>"",
となっていて、 session挟んでいないですね。
User.find_by(email: params[:email].downcase) に。

投稿2021/08/03 04:49

winterboum

総合スコア23416

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

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

Maaxuhbd

2021/08/03 06:55 編集

理解しました。本来のparamsハッシュでは、sessionキーの下にメールアドレスとパスワードが入るような構造だったんですが、form_withを使っているのでsessionキーがないのが問題ですね。 気づけて良かったです。ありがとうございます。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.46%

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

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

質問する

関連した質問