1

我正在启动一个新的 Rails 7 应用程序,最近发现我们不能再使用 ujs 了页面上的功能。

我遇到的问题是我在 ajax:success 进程之后的响应是不可迭代的:

TypeError: object is not iterable (cannot read property Symbol(Symbol.iterator))

下面是我的 HTML、Rails 和 Stimulus 代码:

HTML

<%= form_with model: Article.new, html: { data: { remote: true, type: "html", "action": "ajax:success->modal-forms#onPostSuccess ajax:error->modal-forms#onPostError" } } do |f| %>
  <%= f.label :title, "Article Title" %>
  <%= f.text_field :title, class: "form-control" %>
  <%= f.submit "Save Article", class: "btn btn-primary" %>
<% end %>

红宝石/导轨

def create
  @article = Article.create(article_params)
  if @article.errors.any?
    render partial: 'error', article: @article, status: :bad_request
  else
    render @article
  end
end

这将返回一个基本的 html 页面,该页面将被插入到页面中的另一个位置。

<li><%= @article.title %></li>

刺激作用

onPostSuccess(event) {
  event.preventDefault()
  const [data, status, xhr] = event.detail
  // This is where I get the issue of 'Not Iterable'
}

event.detail给了我不可迭代的错误。有谁知道我如何从 rails 获得我的回复以进行格式化,以便该[data, status, xhr]部分实际工作?

如果为此需要热线或涡轮增压器,则示例将非常有帮助:)

谢谢埃里克

4

1 回答 1

0

这可能不是正确的方法,但它确实有效:

html

<div data-container="remote">
<%= form_with model: Person.new, html: { data: { "action": "submit->remote#submit" } } do |f| %>
    <%= f.text_field :first_name %>
    <%= f.submit :submit %>
  <% end %>
</div>

人轨控制器

def create
    @person = Person.new(person_params)
    if @person.save
      render json: @person
    else
      render partial: 'people/person', locals: { person: @person },  status: :unprocessable_entity
    end
  end

远程刺激控制器

submit(event) {
    event.preventDefault()

    fetch(event.target.action, {
      method: 'POST',
      body: new FormData(event.target),
    }).then(response => {
      console.log(response);
      if(response.ok) {
        return response.json()
      }

      return Promise.reject(response)
    }).then(data => {
      console.log(data)
    }).catch( error => {
      console.warn(error)
    });
  }
于 2022-01-21T21:24:14.927 回答