I am trying to create posts and dynamically generate update forms in the index action. But the forms that are dynamically generated update form are not working. Please find the code below:
posts_controller.rb
class PostsController < ApplicationController
def index
@posts = Post.all
end
def create
@post = Post.new(post_params)
@post.save
end
def update
@post = Post.find(params[:id])
end
private
def post_params
params.require(:post).permit(:title, :content)
end
end
index.html.erb
<h4>Posts</h4>
<table class="table table-bordered table-posts">
<thead>
<tr>
<th>Title</th>
<th>Content</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<% if @posts.present? %>
<% @posts.each do |post| %>
<%= render "posts/table_row", post: post %>
<% end %>
<% else %>
<tr class="no-posts-found">
<td colspan="4" style='text-align: center'>
No posts found.
</td>
</tr>
<% end %>
</tbody>
</table>
<h4>Create Post</h4>
<%= form_for Post.new, url: posts_path, method: :post, html: { remote: true } do |f| %>
<table class="table table-bordered">
<tbody>
<tr>
<td><%= f.text_field :title, class: "form-control", required: true %></td>
<td>
<%= f.text_field :content, class: "form-control", required: true %>
</td>
<td><%= f.submit "Add" %></td>
</tr>
</tbody>
</table>
<% end %>
_table_row.html.erb
<tr class="post-<%= post.id %>">
<%= form_for post, url: posts_path(post), method: :patch, html: { remote: true } do |f| %>
<td><%= f.text_field :title, class: "form-control", required: true %></td>
<td>
<%= f.text_field :content, class: "form-control", required: true %>
</td>
<td>
<%= f.submit "Update" %>
</td>
<% end %>
</tr>
create.js.erb
$("table.table-posts").find("tbody").append("<%= j(render 'posts/table_row', post: @post) %>")
update.js.erb
alert("Updated")