I have been facing problem while creating new book. User is logged in but still it says:
1 error prohibited this book from being saved
When i edit my book it works fine but when i try to create new book it shows .error/
This is book controller:
class BooksController < ApplicationController
before_action :find_book, only:[:show, :edit, :update, :destroy, :upvote]
before_action :authenticate_user!
def index
@books = Book.all.order('created_at DESC')
end
def show
end
def edit
end
def update
if @book.update(book_params)
redirect_to @book
else
render 'edit'
end
end
def destroy
@book.destroy
redirect_to root_path, notice: "successfully deleted"
end
def new
@book =Book.new
end
def create
@book =Book.new(book_params)
if @book.save
redirect_to @book
else
render 'new'
end
end
private
def find_book
@book=Book.find(params[:id])
end
def book_params
params.require(:book).permit(:title, :description, :image)
end
end
My books.rb is:
class Book < ApplicationRecord
#Paperclip.options[:command_path] = 'C:\Program Files\ImageMagick-7.0.5-Q16'
has_attached_file :image, styles: { }
do_not_validate_attachment_file_type :image
#validates_attachment_content_type :image, content_type: /\Aimage\/.*\z/
belongs_to :user
end
You have a belongs_to :user
but user is not set on the Book when you save it.
you can do this:
belongs_to :user, :optional => true
or you can do this:
@user.books.save
don't do this
@book = Book.new
@book.save # No user provided.
And, if you're using a mass assignment, be sure you can set :user_id
or :user
in the book_params as OK to submit in mass assignment.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With