コード ```### 前提・実現したいこと railsでWEBアプリケーションを開発中にエラーが発生してしまった。 これを解決したい。 ### 発生している問題・エラーメッセージ undefined method `id' for nil:NilClass project_controller.rbの4行目で表示された。データベースのUserテーブルにはデータは存在しセッションも正しく機能しているが、なぜ@current_user.idにnilが入ってしまったのか。 御教授頂ければ幸いです。 ### 該当のソースコード application_controller.rb ```ruby``` before_action :set_current_user def set_current_user @current_user = User.find_by(id: session[:user_id]) end
project_controller.rb
def create @project = Project.new( title: params[:title], user_id: @current_user.id ) if @project.save flash[:notice] = "プロジェクトを作成しました" redirect_to("/projects/index") else render("projects/new") end end
user_controller.rb
def create @user = User.new( email: params[:email], password: params[:password] ) @profile = Profile2.new( id: @user.id ) if @user.save && @profile.save session[:user_id] = @user.id flash[:notice] = "ユーザー登録が完了しました" redirect_to("/profiles/#{@user.id}") else render("signup") end end def login @user = User.find_by(email: params[:email]) if @user session[:user_id] = @user.id flash[:notice] = "ログインしました" redirect_to("/profiles/#{@user.id}") else @errors_messages = "メールアドレスまたはパスワードが間違っています" @email = params[:email] @password = params[:password] render("login_form") end end
profile_controller.rb
def create @profile = Profile2.find_by(id: params[:id]) @profile.name = params[:name], @profile.department = params[:department], @profile.year = params[:year], @profile.comment = params[:comment], @profile.contact_info = params[:contact_info], @profile.skill = params[:skill] if @profile.save session[:user_id] = @profile.id flash[:notice] = "プロフィール登録が完了しました" redirect_to("/profile2s/#{@profile.id}") else render("profiles/new") end end
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/06/28 06:07
2019/06/28 07:23
2019/06/28 07:24
2019/06/28 09:08
2019/06/28 09:23
2019/06/28 10:07