在验证失败后,我试图重新显示表单而不丢失数据。
产品型号:
class Book < Sequel::Model
plugin :validation_helpers
def validate
super
validates_presence [:title], message: 'Title is required'
end
end
字符串create.erb
:
...
<%= erb :'partials/flash' %>
...
<form method="post" action="/books/create">
<input name="book[title]" type="text" value="<%= @book.title %>" />
<textarea name="book[description]"><%= @book.description%></textarea>
...
</form>
...
型flash.erb
:
<% flash.map do |f| %>
<div class="alert alert-<%= f[0] %> alert-dismissible fade show" role="alert">
<%= f[1] %>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<% end %>
型BooksController
:
# display a table of books
get '/' do
@books = Book.all
erb :'books/index'
end
# display CREATE form
get '/create' do
@book = Book.new
erb :'books/create'
end
# process CREATE form
post '/create' do
begin
@book = Book.create(params[:book])
flash[:success] = "Book created."
redirect to("/") # /books/
rescue Sequel::ValidationFailed => e
flash[:danger] = @book.errors
redirect to "/create" # redisplay the form
end
end
型
在此过程中,在表单中输入的数据将丢失。
使用最新条目重新显示表单的推荐方法是什么?
编辑新增flash模板
2条答案
按热度按时间xfb7svmp1#
@book.errors
对象示例中获取错误信息或提取信息。yqlxgs2m2#
为了完整起见,最终代码:
控制器:
字符串
表单(使用Bootstrap):
型
validation_errors.erb
:型