Railsでユーザーと入力データの関連付けで困っています。
deviseでユーザー登録機能を実装しました。
入力データは一つのユーザーにつき一つにしたいです。
エラー文は
undefined method `id' for nil:NilClass
というものです。
applicationcontroller
1 2class ApplicationController < ActionController::Base 3 before_action :authenticate_user! 4 before_action :set_current_user 5 6 before_action :configure_permitted_parameters, if: :devise_controller? 7 8 protected 9 10 def configure_permitted_parameters 11 devise_parameter_sanitizer.permit(:sign_up, keys: [:name, :age]) 12 end 13 14 def set_current_user 15 @current_user = User.find_by(id: session[:user_id]) 16 end 17end 18 19
modelsuser
1class User < ApplicationRecord 2 # Include default devise modules. Others available are: 3 # :confirmable, :lockable, :timeoutable and :omniauthable 4 devise :database_authenticatable, :registerable, 5 :recoverable, :rememberable, :trackable, :validatable 6 7 belongs_to :user 8end 9
modelspost
1class Post < ApplicationRecord 2 belongs_to :user 3 validates :content, {presence: true , length: {maximum: 30}} 4 validates :user_id, {presence: true} 5 6end 7
homecontroller
1class HomeController < ApplicationController 2 def index 3 @posts = Post.all.order(created_at: :desc) 4 end 5 6 def new_fc 7 8 end 9 10 def create 11 @post = Post.new( 12 content: params[:content], 13 user_id: @current_user.id 14 ) 15 16 if @post.save 17 redirect_to("/") 18 else 19 render("new_fc") 20 end 21 end 22 23 def show_fc 24 @post = Post.find_by(id: params[:id]) 25 end 26 27 def edit_fc 28 @post = Post.find_by(id: params[:id]) 29 end 30 31 def update_fc 32 @post = Post.find_by(id: params[:id]) 33 @post.content = params[:content] 34 if @post.save 35 flash[:notice] = "編集完了!!!" 36 redirect_to("/#{@post.id}/show_fc") 37 else 38 render("edit_fc") 39 end 40 end 41 42 def profile 43 end 44end 45
viewsnewfchtml
1<h3>ファンクラブ名を入力してね!<h3> 2 3<%= form_tag("/home/create") do %> 4 <textarea name="content"></textarea> 5 <input type="submit" value="次へ"></input> 6<% end %> 7
routes
1Rails.application.routes.draw do 2 devise_for :users 3 root 'home#index' 4 get "home/new_fc" => "home#new_fc" 5 post "home/create" => "home#create" 6 get "home/profile" => "home#profile" 7 get ":id/show_fc" => "home#show_fc" 8 get ":id/edit_fc" => "home#edit_fc" 9 post ":id/update_fc" => "home#update_fc" 10end 11
原因がどこにあるのかわからないのでありそうなところのコードを載せました。おたすけください。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/08/14 14:49