【问题标题】:1 error prohibited this book from being saved [closed]1 个错误禁止保存此书 [关闭]
【发布时间】:2017-03-13 19:44:39
【问题描述】:

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

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 

【问题讨论】:

  • 你可能会尝试找出错误的原因,比如这个帖子:stackoverflow.com/a/42629794/6780663
  • 代码在哪里?我们能提供什么帮助?
  • 您的book 模型上似乎有一个user_id,请确保user 设置在book 上。更多代码对于正确回答您的问题非常有用!
  • @Ursus 我已经编辑了我的问题希望这是可以理解的
  • @Gabriel Lett 我已经编辑了我的问题希望这是可以理解的

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


【解决方案1】:

您有一个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 设置为可以批量作业提交。

【讨论】:

  • 请选择optional: truerequired 已弃用
猜你喜欢
  • 2019-06-07
  • 1970-01-01
  • 1970-01-01
  • 2014-07-14
  • 1970-01-01
  • 2011-04-18
  • 1970-01-01
  • 2014-11-05
  • 1970-01-01
相关资源
最近更新 更多