简体   繁体   中英

loop through a Form_for rails

I have "rails generated scaffold Post" and im trying to convert the posts.each index to form_for so I can use "remote: true" the AJAX.

Problem : My code doesn't show my records. It just displays the table thread headings.

    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

^^^ So i have only made these change to the controller and the following code is failing to display the post records

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

You should render your form_for line, it's not enough just to render fields.

Try using:

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

instead of:

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

I think you have got a bit confused somewhere along the way.

You don't need to use form_for to be able to do AJAX requests and you have quite a few bugs anyway in the way you have implemented it.

If I understand your requirements correctly it seems what you are attempting to do is simply display the posts in a table with links to the show, edit, destroy actions for each entry. Those links you want to invoke as AJAX requests.

To get you started:

  1. Change the index action to simply:

    def index @posts = Post.all end

  2. The tbody declaration should become:

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

  3. Create a _post.html.erb partial that will be responsible for rendering each row of the table:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM