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 %>
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:
Change the index action to simply:
def index
@posts = Post.all
end
The tbody declaration should become:
<tbody>
<%= render @posts %>
</tbody>
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>