1错误禁止保存此书

时间:2017-03-13 19:44:40

标签: ruby-on-rails ruby ruby-on-rails-5

我在创作新书时遇到了问题。 用户已登录,但仍然显示:

1错误禁止本书被保存

  • 用户必须存在

当我编辑我的书时,它工作正常,但当我尝试创建新书时,它会显示.error /

这是图书管理员:

    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

我的books.rb是:

 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 

1 个答案:

答案 0 :(得分:5)

您可能拥有belongs_to:user,并且在保存时未在Book上设置用户。

你可以这样做:

belongs_to :user, :optional => true

或者你可以这样做:

@user.books.save

不要这样做

@book = Book.new
@book.save           # No user provided.

并且,如果您正在使用批量作业,请确保您可以将book_params中的:user_id:user设置为可以提交作为批量作业。