1 error prohibited this book from being saved [closed]
Asked Answered
H

1

7

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

  • User must exist

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 
Hexagram answered 13/3, 2017 at 19:44 Comment(5)
You migth try to find out the cause of the error, with something like this post: https://mcmap.net/q/1479565/-ruby-begin-transaction-rollback-transactionIcian
Where's the code? How can we help?Imperialism
It looks like your book model has an user_id on it, make sure the user is being set on the book. More code would be very useful to properly answer your question!Naoise
@Imperialism i have edited my question hope this will be understandableHexagram
@Gabriel Lett i have edited my question hope this will be understandableHexagram
D
12

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.

Dulcet answered 13/3, 2017 at 20:11 Comment(1)
please, prefer optional: true, required is deprecatedImperialism

© 2022 - 2024 — McMap. All rights reserved.