我在rails中的Book表单中收到此错误:
表单中的第一个参数不能包含nil或为空
表格的
<%= form_for @book, html: { multipart: true } do |f| %>
<% if @book.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@book.errors.count, "error") %> prohibited this book from being saved:</h2>
<ul>
<% @book.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :title %><br>
<%= f.text_field :title %>
</div>
<div class="field">
<%= f.label :author %><br>
<%= f.text_field :author %>
</div>
<div class="field">
<%= f.label :language %><br>
<%= f.text_field :language %>
</div>
<div class="field">
<%= f.label :year %><br>
<%= f.text_field :year %>
</div>
<div class="field">
<%= f.label :description %><br>
<%= f.text_area :description %>
</div>
<div class="field">
<%= f.label :total_pages %><br>
<%= f.text_field :total_pages %>
</div>
<div class="field">
<%= f.label :rating %><br>
<%= f.text_field :rating %>
</div>
<div class="field">
<%= f.label :image %><br>
<%= f.file_field :image %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
控制器
class BooksController < ApplicationController
before_action :set_book, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!, except: [:index, :show]
def search
if params[:search].present?
@books = Book.search(params[:search])
else
@books = Book.all
end
end
def index
@books = Book.all
end
def show
@reviews = Review.where(book_id: @book.id).order("created_at DESC")
if @reviews.blank?
@avg_review = 0
else
@avg_review = @reviews.average(:rating).round(2)
end
end
end
def new
@book = current_user.books.build
end
def edit
end
def create
@book = current_user.books.build(book_params)
respond_to do |format|
if @book.save
format.html { redirect_to @book, notice: 'Book was successfully created.' }
format.json { render :show, status: :created, location: @book }
else
format.html { render :new }
format.json { render json: @book.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if @book.update(book_params)
format.html { redirect_to @book, notice: 'Book was successfully updated.' }
format.json { render :show, status: :ok, location: @book }
else
format.html { render :edit }
format.json { render json: @book.errors, status: :unprocessable_entity }
end
end
end
def destroy
@book.destroy
respond_to do |format|
format.html { redirect_to books_url, notice: 'Book was successfully destroyed.' }
format.json { head :no_content }
end
end
private
def set_book
@book = Book.find(params[:id])
end
def book_params
params.require(:book).permit(:title, :author, :language, :year, :description, :total_pages, :rating, :image)
end
我遇到了相关错误,但没有一个解决方案似乎符合我的特定问题。可能导致这种情况的任何线索?
答案 0 :(得分:1)
您收到错误是因为@book
为零。
确保您已使用相应控制器@book
中的@book = Book.new
初始化action
,以便@book
可用于包含该表单的视图。
答案 1 :(得分:0)
在控制器操作中初始化@book = Book.new