我收到一条错误消息,指出我的show.html.erb页面中未定义的方法'name'。如果它说@ book.category.name,它会一直说未定义的方法名称。
show.html.erb
mix phoenix.server
Books_Controller.rb
while(move <= 0 || move >= 10 )
{
System.out.println("that move is invalid must be 1-9");
System.out.print("Where do you want to move? ");
move = in.nextInt();
}
Book.rb
<h1><%= @book.title %></h1>
<h3><%= @book.author %></h3>
<h4>Category: <%= @book.category.name %></h4>
<p><%= @book.description %></p>
<%= link_to "Back", root_path %>
<% if user_signed_in? %>
<% if @book.user_id == current_user.id %>
<%= link_to "edit", edit_book_path(@book) %>
<%= link_to "Delete", book_path(@book), method: :delete, data: {confirm: "Are you sure you want to delete book?"} %>
<% end %>
<% end %>
Category.rb
class BooksController < ApplicationController
before_action :find_book, only: [:show, :edit, :destroy, :update]
def index
if params[:category].blank?
@books = Book.all.order("created_at DESC")
else
@category_id = Category.find_by(name: params[:category]).id
@books = Book.where(:category_id => @category_id).order("created_at DESC")
end
end
def show
end
def new
@book = current_user.books.build
@categories = Category.all.map{ |c| [c.name, c.id]}
end
def create
@book = current_user.books.build(book_params)
@book.category_id = params[:category_id]
if @book.save
redirect_to root_path
else
render 'new'
end
end
def edit
@categories = Category.all.map{ |c| [c.name, c.id]}
end
def update
@book.category_id = params[:category_id]
if @book.update(book_params)
redirect_to book_path(@book)
else
render ' new'
end
end
def destroy
@book.destroy
redirect_to root_path
end
private
def book_params
params.require(:book).permit(:title, :description, :author, :category_id, :book_img)
end
def find_book
@book = Book.find(params[:id])
end
end
答案 0 :(得分:1)
如果您必须将类别留空,请使用#try
:
<h4>Category: <%= @book.category.try(:name) %></h4>
答案 1 :(得分:0)
您需要确保实例@book
具有category
对象。
<h4>Category: <%= @book.category ? @book.category.name : "This book has no category" %></h4>