1 个错误禁止保存这本书 [英] 1 error prohibited this book from being saved

查看:41
本文介绍了1 个错误禁止保存这本书的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have been facing problem while creating new book. User is logged in but still it says:

1 个错误禁止保存此书

1 error prohibited this book from being saved

  • 用户必须存在

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

When i edit my book it works fine but when i try to create new book it shows .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 是:

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 

推荐答案

您有一个 belongs_to :user 但保存时未在 Book 上设置用户.

You have a belongs_to :user but user is not set on the Book when you save it.

你可以这样做:

belongs_to :user, :optional => true

或者你可以这样做:

@user.books.save

不要这样做

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

而且,如果您使用的是批量分配,请确保您可以将 book_params 中的 :user_id:user 设置为 OK 以提交批量分配.

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.

这篇关于1 个错误禁止保存这本书的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆