ruby-on-rails - 1 个错误禁止保存此书

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

<分区>

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

1 个错误禁止保存这本书

  • 用户必须存在

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

这是图书 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

我的 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 

最佳答案

你有一个 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 以提交批量分配。

关于ruby-on-rails - 1 个错误禁止保存此书,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42772143/

相关文章:

ruby-on-rails - 我可以找到所有值,例如[[_bc],​​“a_c”,“ab_”]

ruby-on-rails - 为 Rails Assets 设置缓存控制

ruby-on-rails - ruby rails : How do you list the partial paths that are rendered for a page?

ruby-on-rails - Rails 远程表单 collection_select onchange 错误

ruby-on-rails - 将 rails_admin 与 rails_api 一起使用

ruby-on-rails - 在 yaml 列表中插入?

ruby-on-rails - activerecord 比较时间

ruby-on-rails - 使用 Devise 一次登录的多个模型?

ruby-on-rails - 使用 Ruby on Rails 格式化日期

ruby - 将选项传递给 thor 中的模板函数