I am getting an error message that says undefined method 'name' in my show.html.erb page. Where it says @book.category.name it keeps saying undefined method name.
show.html.erb
<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 %>
Books_Controller.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
Book.rb
class Book < ActiveRecord::Base
belongs_to :user
belongs_to :category
has_attached_file :book_img, :styles => { :book_index => "250x350>", :book_show => "325x475>" }, :default_url => "/images/:style/missing.png"
validates_attachment_content_type :book_img, :content_type => /\Aimage\/.*\Z/
end
Category.rb
class Category < ActiveRecord::Base
has_many :books
end
Aucun commentaire:
Enregistrer un commentaire