ruby 在Sinatra应用程序中重新显示窗体而不丢失数据

xmq68pz9  于 2023-08-04  发布在  Ruby
关注(0)|答案(2)|浏览(117)

在验证失败后,我试图重新显示表单而不丢失数据。
产品型号:

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">&times;</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模板

xfb7svmp

xfb7svmp1#

  • 而不是在postrescue部分重定向,再次呈现createformtemplate,这将访问books示例和与之关联的错误
  • 表单渲染后,使用books示例来显示创建表单模板中的错误,如果你想使用flash,那么你需要从@book.errors对象示例中获取错误信息或提取信息。
yqlxgs2m

yqlxgs2m2#

为了完整起见,最终代码:
控制器:

post '/create' do

    begin

        @book = Book.new(params[:book])
        @book.save

        flash[:success] = "Book created."
        redirect to("/")

    rescue Sequel::ValidationFailed => e
        erb :'books/create'

    rescue => e
        flash[:danger] = e.message
        erb :'books/create'

    end

end

字符串
表单(使用Bootstrap):

<form method="post" action="/books/create">
  <div class="form-group">
    <label for="inputTitle">Title</label>
    <input id="inputTitle" name="book[title]" type="text" class="form-control <%= 'is-invalid' if @book.errors[:title] %>" placeholder="Title" value="<%= @book.title %>">
    <%= erb :'partials/validation_errors', locals: {field: :title, errors: @book.errors} %>
  </div>
  ...
</form>


validation_errors.erb

<% if locals[:errors].has_key?(locals[:field]) %>
<div class="invalid-feedback">
    <ul>
        <% locals[:errors][locals[:field]].each do |error| %>
        <li><%= error %></li>
        <% end %>
    </ul>
</div>
<% end %>

相关问题