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

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

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

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

Q&A

解決済

1回答

1297閲覧

新規投稿後のredirectでNoMethodError

退会済みユーザー

退会済みユーザー

総合スコア0

Ruby on Rails

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

0グッド

0クリップ

投稿2019/12/05 14:11

本の投稿ができるアプリを作成しています。
新規投稿後に/users/:idのページへリダイレクトしたいのですが、そこでエラーが発生しております。

NoMethodError in BooksController#create undefined method `id' for nil:NilClass Extracted source (around line #8): 6 book.user_id = current_user.id 7 book.save! 8 redirect_to user_url(@user.id)←エラー箇所 9 end 10 11 def index

初めはログインができていないことが原因かと思いましたができており、一度ログアウトした後に再ログインすると投稿が表示されます。
redirect_toでidの取得ができていないと予想しましたが、解決できませんでした。

books_controller.rb class BooksController < ApplicationController before_action :authenticate_user!, only: [:show] def create book = Book.new(book_params) book.user_id = current_user.id book.save! redirect_to user_url(@user.id) end def index end def show @book = Book.find(params[:id]) book = book.all end def edit @book = Book.find(params[:id]) end def update @book = Book.find(params[:id]) book.update(book_params) redirect_to user_path(@user) end private def book_params params.require(:book).permit(:title, :body) end end
users/show.html.erb <%= render 'shared/header' %> <div class="top"> <div class="container"> <div class="row"> <div class="col-lg-3"> <p>User info</p> <%= attachment_image_tag @user, :profile_image, :fill, 250, 250, format: 'jpeg', fallback: "no_image.jpg", size:'250x250' %> <table class="table"> <tr>    <th>name</th>    <th><%= current_user.name %></th>   </tr>   <tr>    <th>introduction</th>    <th><%= current_user.introduction %></th>    </tr> </table> <%= link_to edit_user_path, class: "btn btn-default" do %> <i class="fa fa-wrench"></i> <% end %> <p>New book</p> <%= form_for @book do |f| %> <p>Title</p> <%= f.text_field :title %> <p>Opinion</p> <%= f.text_area :body %> <%= f.submit 'Create Book' %> <% end %> </div> <div class="col-lg-9"> <p>Books</p> <table class="table table-hover"> <thead> <tr> <th></th> <th>Title</th> <th>Opinion</th> </tr> </thead> <% @books.each do |book| %> <tbody> <tr> <td><%= book.user_id %><%= attachment_image_tag @user, :profile_image, :fill, 50, 50, format: 'jpeg', fallback: "no_image.jpg", size:'50x50' %><br><%= book.user.name %></td> <td><%= book.user_id %><%= book.title %></td> <td><%= book.user_id %><%= book.body %></td> </tr> </tbody> <% end %> </table> </div> </div> </div> </div> <%= render 'shared/footer' %>
user.rb class User < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable has_many :books, dependent: :destroy attachment :profile_image end
book.rb class Book < ApplicationRecord belongs_to :user end
$ rake routes Prefix Verb URI Pattern Controller#Action new_user_session GET /users/sign_in(.:format) users/sessions#new user_session POST /users/sign_in(.:format) users/sessions#create destroy_user_session DELETE /users/sign_out(.:format) users/sessions#destroy new_user_password GET /users/password/new(.:format) devise/passwords#new edit_user_password GET /users/password/edit(.:format) devise/passwords#edit user_password PATCH /users/password(.:format) devise/passwords#update PUT /users/password(.:format) devise/passwords#update POST /users/password(.:format) devise/passwords#create cancel_user_registration GET /users/cancel(.:format) users/registrations#cancel new_user_registration GET /users/sign_up(.:format) users/registrations#new edit_user_registration GET /users/edit(.:format) users/registrations#edit user_registration PATCH /users(.:format) users/registrations#update PUT /users(.:format) users/registrations#update DELETE /users(.:format) users/registrations#destroy POST /users(.:format) users/registrations#create root GET / top#top home_about GET /home/about(.:format) top#home users GET /users(.:format) users#index POST /users(.:format) users#create new_user GET /users/new(.:format) users#new edit_user GET /users/:id/edit(.:format) users#edit user GET /users/:id(.:format) users#show PATCH /users/:id(.:format) users#update PUT /users/:id(.:format) users#update DELETE /users/:id(.:format) users#destroy books GET /books(.:format) books#index POST /books(.:format) books#create new_book GET /books/new(.:format) books#new edit_book GET /books/:id/edit(.:format) books#edit book GET /books/:id(.:format) books#show PATCH /books/:id(.:format) books#update PUT /books/:id(.:format) books#update DELETE /books/:id(.:format) books#destroy refile_app /attachments #<Refile::App app_file="/home/ec2-user/.rvm/gems/ruby-2.6.3/bundler/gems/refile-46b4178654e6/lib/refile/app.rb">

お気づきの点がありましたらご指摘をお願いします。

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

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

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

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

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

guest

回答1

0

ベストアンサー

@user って何者でしょう?どこにも定義がない。
今 book をcreateさせた人、で良いなら 
redirect_to user_url(current_user.id)

redirect_to user_url(current_user)
でもよかったとおもう

でないなら、@userって何者なのか、を定義して下さい

投稿2019/12/05 14:17

winterboum

総合スコア23284

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

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

退会済みユーザー

退会済みユーザー

2019/12/05 14:28

ご回答頂きありがとうございます。 redirect_to user_url(current_user.id)で表示させることができました。 「@userを定義する」ということが何なのかいまいち理解できていない状態です。 同じbooks_controller.rb内に、@user=で代入されているものがないということでしょうか? 続けて質問してしまい申し訳ございません。
winterboum

2019/12/05 21:52

そうです。 redirect_to user_url(@user.id) ということは@userについて表示するということですから、@userって誰なのかを指定(代入)しておく必要があります
退会済みユーザー

退会済みユーザー

2019/12/06 07:47

@userは同じアクション内に定義しなければいけないのでしょうか?
winterboum

2019/12/06 07:52

最初はそれが一番良いでしょう。 インスタンス変数ですので、同じインスタンスの中の他のmethodで定義しても良いですが、ただしそのmethodの方が先に実行されないといけないので、始めはややこしいでしょ8う
退会済みユーザー

退会済みユーザー

2019/12/06 08:37

親切に教えて頂き大変助かりました。 ありがとうございました。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.50%

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

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

質問する

関連した質問