undefined method `new_record?' for nil:NilClassを解決したいです。
新規投稿画面と編集画面を部分テンプレートで作成し
submitボタンの表示する文字をファイルによって変えたいです。新規投稿時はCreateBook、編集の時はUpdateBookが表示されるようにしたいです。
その際あるサイト(https://teratail.com/questions/312875)を参考に
_form.html.erb
RubyonRails
<% if f.object.new_record? %> <%= f.submit "Create Book", class: "btn btn-success" %> <% else %> <%= f.submit "Update Book", class: "btn btn-success" %> <% end %>
を記述した所、userのshow.html.erb(userの詳細ページ)でエラーが発生しました
(サイトにあるようにnew_record?メソッドを自分で定義する必要は無いと思います)
(新規投稿のページや投稿を編集するページではエラーは発生していません)
発生している問題・エラーメッセージ
NoMethodError in Users#show
Showing /home/ec2-user/environment/bookers2-debug/app/views/books/_form.html.erb where line #21 raised:
undefined method `new_record?' for nil:NilClass
Extracted source (around line #21):
19
20
21
22
23
24
<% if f.object.new_record? %> <%= f.submit "Create Book", class: "btn btn-success" %> <% else %> <%= f.submit "Update Book", class: "btn btn-success" %>
Trace of template inclusion: app/views/users/show.html.erb
Rails.root: /home/ec2-user/environment/bookers2-debug
Application Trace | Framework Trace | Full Trace
app/views/books/_form.html.erb:21:in block in _app_views_books__form_html_erb__3555135995817864763_70203137971340' app/views/books/_form.html.erb:1:in
_app_views_books__form_html_erb__3555135995817864763_70203137971340'
app/views/users/show.html.erb:8:in `_app_views_users_show_html_erb___123336745112956188_70203137756200'
Request
Parameters:
{"id"=>"1"}
Toggle session dump
Toggle env dump
Response
Headers:
None
該当のソースコード
books/_form.html.erb
RubyonRails
<%= form_with model:book,local:true do |f| %> <div class="form-group"> <%= f.label :title %> <%= f.text_field :title, class: 'form-control book_title' %> </div> <div class="form-group"> <%= f.label :opinion %> <%= f.text_area :body, class: 'form-control book_body' %> </div> <div class="form-group"> <% if f.object.new_record? %> <%= f.submit "Create Book", class: "btn btn-success" %> <% else %> <%= f.submit "Update Book", class: "btn btn-success" %> <% end %> </div> <% end %>
user/show.html.erb
RubyonRails
<div class='container px-5 px-sm-0'> <div class='row'> <div class='col-md-3'> <h2>User info</h2> <%= render 'info', user: @user %> <h2 class="mt-3">New book</h2> <%= render 'books/form', book: @book_form %> </div> <div class='col-md-8 offset-md-1'> <h2>Books</h2> <%= render 'books/index',books: @books %> </div> </div> </div>
books_controller.rb
RubyonRails
class BooksController < ApplicationController before_action :correct_user, only: [:edit, :update] def show @book_form = Book.new @book = Book.find(params[:id]) @user = @book.user end def index @books = Book.all @book = Book.new end def create @book = Book.new(book_params) @book.user_id = current_user.id if @book.save redirect_to book_path(@book), notice: "You have created book successfully." else @books = Book.all render 'index' end end def edit @book = Book.find(params[:id]) end def update @book = Book.find(params[:id]) if @book.update(book_params) redirect_to book_path(@book), notice: "You have updated book successfully." else render "edit" end end def destroy @book = Book.find(params[:id]) @book.destroy redirect_to books_path end private def book_params params.require(:book).permit(:title, :body) end def correct_user @book = Book.find(params[:id]) @user = @book.user redirect_to(books_path) unless @user == current_user end end
users_controller.rb
RubyonRails
class UsersController < ApplicationController before_action :ensure_correct_user, only: [:update, :edit] def show @user = User.find(params[:id]) @books = @user.books @book = Book.new end def index @users = User.all @book = Book.new end def edit @user = User.find(params[:id]) end def update if @user.update(user_params) redirect_to user_path(@user), notice: "You have updated user successfully." else @user = User.find(params[:id]) @books = @user.books @book = Book.new render "show" end end private def user_params params.require(:user).permit(:name, :introduction, :profile_image) end def ensure_correct_user @user = User.find(params[:id]) unless @user == current_user redirect_to user_path(current_user) end end end
models/book.rb
RubyonRails
class Book < ApplicationRecord belongs_to :user validates :title, presence: true validates :body, presence: true, length: {maximum: 200} end
models/user.rb
RubyonRails
class User < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable has_many :books attachment :profile_image, destroy: false validates :name, length: {maximum: 20, minimum: 2}, uniqueness: true validates :introduction, length: {maximum: 50} end
試したこと
自分で調べた所、Rubyのnew_record?メソッドを使うことはわかったが
使い方まではわからなかった
エラー文よりobjectが空だと思い、
objectの部分をbookにしたが
解決には至らなかった
gemをインストールするのかと思い、gem new_record?で調べたが
解決には至らなかった
補足情報(FW/ツールのバージョンなど)
バージョン
Rails 5.2.5
ruby 2.6.3p62 (2019-04-16 revision 67580) [x86_64-linux]
まだ回答がついていません
会員登録して回答してみよう