【问题标题】:loop through a Form_for rails循环通过 Form_for rails
【发布时间】:2016-10-28 17:45:29
【问题描述】:

我有“rails 生成的脚手架 Post”,我正在尝试将 posts.each 索引转换为 form_for,以便我可以使用“remote: true”AJAX。

问题:我的代码没有显示我的记录。它只显示表线程标题。

    class PostsController < ApplicationController
  before_action :set_post, only: [:show, :edit, :update, :destroy]

  # GET /posts
  # GET /posts.json
  def index
    @posts = Post.all
    @post = Post.new
  end

  # GET /posts/1
  # GET /posts/1.json
  def show
  end

  # GET /posts/new
  def new
    @post = Post.new
  end

  # GET /posts/1/edit
  def edit
  end

^^^ 所以我只对控制器进行了这些更改,以下代码无法显示帖子记录

<tbody>
<% @posts.each do |mend| %>
<% form_for(mend) do |f| %>
  <tr>
    <td><%= f.text_field :title %></td>
    <td><%= f.text_field :content %></td>
    <td><%= f.text_field :verify %></td>
    <td><%= f.text_field :date %></td>
    <td><%= f.text_field :rate %></td>
    <td><%= link_to 'Show', post_path(f) %></td>
    <td><%= link_to 'Edit', edit_post_path(f) %></td>
    <td><%= link_to 'Destroy', @post, method: :delete, data: { confirm: 'Are you sure?' } %></td>
  </tr>
<% end %>
<% end %>

【问题讨论】:

  • 你想完成什么?
  • 我正在尝试获取将所有记录列为帖子内容的代码。我需要使用 form_for

标签: ruby-on-rails ajax foreach form-for


【解决方案1】:

我认为您在此过程中的某个地方有些困惑。

您不需要使用 form_for 来执行 AJAX 请求,而且您在实现它的方式上也有很多错误。

如果我正确理解您的要求,您似乎只是在表格中显示帖子,其中包含指向每个条目的显示、编辑、销毁操作的链接。您希望作为 AJAX 请求调用的那些链接。

让您开始:

  1. 将索引操作更改为简单:

    def index @posts = Post.all end

  2. tbody 声明应该变成:

    <tbody> <%= render @posts %> </tbody>

  3. 创建一个_post.html.erb partial,负责渲染表格的每一行:

    <tr> <td><%= @post.title %></td> <td><%= @post.content %></td> <td><%= @post.verify %></td> <td><%= @post.date %></td> <td><%= @post.rate %></td> <td><%= link_to 'Show', post_path(@post), remote: true %></td> <td><%= link_to 'Edit', edit_post_path(@post), remote: true %></td> <td><%= link_to 'Destroy', @post, method: :delete, data: { confirm: 'Are you sure?' }, remote: true %></td> </tr>

【讨论】:

  • 但如果我想要整个部分,以便我可以在哪里操作它,我放置“remote: true”
  • 不确定我是否遵循 - 我已将 remote: true 语句添加到 link_to helpers
【解决方案2】:

你应该渲染你的 form_for 行,仅仅渲染字段是不够的。

尝试使用:

<%= form_for(mend) do |f| %>

代替:

<% form_for(mend) do |f| %>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-22
    • 2012-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多