【问题标题】:Rails AJAX form not re-populating fields after validation fail验证失败后,Rails AJAX 表单未重新填充字段
【发布时间】: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


【解决方案1】:

我猜问题是你在这里使用Note.new

<%= 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 %>

因此,表单中永远不会有任何值,因为表单始终基于新的Note 对象。

由于您在 newcreate 操作中都实例化了 @note,我相信您应该这样做:

<%= simple_form_for [book, @note], 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 %>

我不使用simple_form,所以这是在黑暗中拍摄。

另外,正如 John Gallagher 在 cmets 中所说的那样:

@note = @book.notes.create(note_params)

应该是这样的:

@note = @book.notes.build(note_params)

当实例化@note 之类的东西时,通常使用.build 而不是.create,因为.build 不会保存@note,这使得if @note.save 的条件更加合理。

【讨论】:

    猜你喜欢
    • 2010-12-30
    • 2014-03-29
    • 1970-01-01
    • 1970-01-01
    • 2011-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多