【发布时间】:2019-02-01 18:21:24
【问题描述】:
我有一个带有 simple_form gem 的 Rails 5.2.0 应用程序。在下面的设置中,我正在使用 AJAX 表单创建一个新的Note。我可以创建一个新记录就好了。
但是,当表单验证失败(标题和正文属性)时,它会重新呈现 _new.html.erb 部分,但不会使用用户提交表单之前存在的数据填充表单字段。
验证失败后如何保留数据?
book.rb
class Book < ApplicationRecord
has_many :notes
end
note.rb
class Note < ApplicationRecord
belongs_to :book
validates :title, :body, presence: true
end
notes_controller.rb
def new
@note = Note.new
@book = Book.find(params[:book_id])
respond_to do |format|
format.html {}
format.js {}
end
end
def create
@book = Book.find(params[:book_id])
@note = @book.notes.create(note_params)
if @note.save
respond_to do |format|
format.html { redirect_to user_book_path(id: @book.id, user_id: current_user.slug) }
format.js { redirect_to user_book_path(id: @book.id, user_id: current_user.slug) }
end
else
respond_to do |format|
format.html { render :new }
format.js {render :new}
end
end
end
_new.html.erb
<%= simple_form_for [book, Note.new], remote: true do |f| %>
<%= f.input :title, placeholder: "title", label: false, autofocus: true %>
<%= f.input :body, placeholder: "title", label: false, autofocus: true %>
<%= f.button :submit, "Create note" %>
<% end %>
new.js.erb
$("#show-edit-note").html("<%= j render partial: 'notes/new', locals: { book: @book, note: @note } %>");
【问题讨论】:
-
添加所需的表单属性,以验证客户端的存在!
标签: ruby-on-rails ruby ajax