ruby-on-rails - Ruby on Rails 表单错误未提供任何输出/不工作
问题描述
大家好,我到处搜索如何输出表单错误,但没有运气。我尝试了几乎所有在互联网上找到的代码,但仍然无法正常工作。
以下是我的一些文件:
查看/书籍/new.html.erb
<div class="container">
<h2>Create a new book</h2>
<%= form_with model: @book, url: create_new_book_path do |f| %>
<% if @book.errors.any? %>
<ul>
<% @book.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
<% end %>
<div class="form-group row">
<%= label_tag(:title, "Title:", class: "col-sm-2 col-form-label") %>
<div class="col-sm-10">
<%= f.text_field :title, class: "form-control" %>
</div>
</div>
<div class="form-group row">
<%= label_tag(:price, "Price:", class: "col-sm-2 col-form-label") %>
<div class="col-sm-10">
<%= f.text_field :price, class: "form-control" %>
</div>
</div>
<div class="form-group row">
<%= label_tag(:subject_id, "Subject:", class: "col-sm-2 col-form-label") %>
<div class="col-sm-10">
<%= f.collection_select :subject_id, @subjects, :id, :name, class: "form-control" %>
</div>
</div>
<div class="form-group row">
<%= label_tag(:description, "Book description:", class: "col-sm-2 col-form-label") %>
<div class="col-sm-10">
<%= f.text_area :description, class: "form-control" %>
</div>
</div>
<%= submit_tag "Create book", class: "btn btn-success" %>
<%= link_to "Cancel", books_path, class: "btn btn-danger" %>
<% end %>
<br/>
</div>
book_controller.rb
class BooksController < ApplicationController
def index
@books = Book.all
end
def show
@book = Book.find(params[:id])
end
def new
@book = Book.new
@subjects = Subject.all
end
def create
@book = Book.new(book_params)
end
def book_params
params.require(:book).permit(:title, :price, :subject_id, :description)
end
def edit
@book = Book.find(params[:id])
@subjects = Subject.all
end
def update
@book = Book.find(params[:id])
if @book.update_attributes(book_params)
redirect_to action: "index"
else
@subjects = Subject.all
render action: "edit"
end
end
def destroy
Book.find(params[:id]).destroy
redirect_to action: "index"
end
end
路线.rb
get 'books/new', to: 'books#new', as: 'new_book'
post 'books/create', to: 'books#create', as: 'create_new_book'
查看/布局/application.html.erb
<main role="main">
<%= yield %>
</main>
我真的不知道我错过了什么来获得错误,感谢您的回答!
解决方案
尝试像这样将它们放在闪光灯中并在您的视图中呈现
def create
@book = Book.new
if @book.update(book_params)
flash[:notice] = 'success'
redirect_to action: 'index'
else
flash[:alert] = @book.errors.full_messages.join(', ')
redirect_to action: 'index'
end
end
并在您的视图中渲染那些闪烁,例如
<% if flash[:notice]%>
<span class='notice'><%= flash[:notice] %></span>
<% end %>
<% if flash[:alert]%>
<span class='alert'><%= flash[:alert] %></span>
<% end %>
推荐阅读
- python - 比较两个整数时 if 语句不起作用
- ios - 导入数据后如何重新加载 UITableView?
- ios - CAShapeLayer() 绘制奇怪的线/路径
- python-3.x - 我如何为这个问题编写 python 代码?
- html - 如何将 css 文件正确添加到 php 文件中
- python - 以毫秒为单位分配时间以获得平滑曲线
- python - 不确定如何使用 tkinter 条目来运行 if 语句
- flutter - ListVIew 再次构建后不会滚动到正确的偏移位置
- python - 向后打印列表
- mysql - 我可以加速这个查询(AWS)mysql db的VBA函数吗?