0

我有一个模型叫adventurer. 我可以使用远程表单创建一个:

<%= simple_form_for @adventurer, validate: true, remote: true, do |adventurer| %>
# ...

我的create动作是这样的:

  def create
    @adventurer = Adventurer.new(safe_params)
    @adventurer.save

    respond_to do |format|
      format.js
    end
  end

我想在 JS 而不是控制器中处理成功和失败的结果。

<% if @applicant.errors.any? %>
  console.log('It failed :(');
<% else %>
  console.log('Success!');
<% end %>

知道上面的示例有效,我想对其进行修改,以便它可以处理错误消息。

以下导致控制台中出现错误SyntaxError: Unexpected token '&'. Expected a property name.

<% if @adventurer.errors.any? %>
  errors = <%= @adventurer.errors.to_json %>
  console.log(errors[:full_messages]);
<% else %>
  console.log('Success!');
<% end %>

这让我相信我没有以正确的方式将 Ruby 集合传递给 JS。如何使#errors.full_messages我的 JS 模板可用?

4

1 回答 1

3
  1. console.log(errors[:full_messages]);是无效的语法,JS 中没有像 Ruby 那样的符号语法。它应该是errors.full_messages或者errors['full_messages']如果你想full_massages在 JS 中访问一个对象上的 prop
  2. @adventurer.errors.to_json将返回这样的 JSON {"error_key1": "error_messsage1", "error_key2": "error_message2"}。因此,如您所见,这里没有full_messages道具。但是你也可以这样做@adventurer.errors.full_messages.to_json,它将返回数组中的完整消息。
  3. 您需要将此 JSON 插入为raw字符串:errors = <%= raw @adventurer.errors.to_json %>正确将其传递给 JS
于 2019-07-29T17:05:56.113 回答