I'm a beginner in Ruby on Rails. I'm trying to learn using Ajax with Rails. So far so good, I've made basic CRUD operations using Ajax.
But the problem is, for example, when creating a new post
, It's created only once. But after clicking on one of the pagination links. It's created twice. If I clicked for the third time and added new post
, It's added three times.
The same goes with deletion (ie confirmation window is presented three times if clicked on three pagination links)
Note, pagination is not using Ajax.
Here's my code:
posts_controller.rb
class PostsController < ApplicationController
before_action :get_all, only: [:index, :create, :destroy]
def index
@post = Post.new
end
def new
@post = Post.new
end
def create
@post = Post.new(post_params)
if @post.save
@post = Post.new
respond_to do |format|
format.html { redirect_to posts_url}
format.js
end
else
respond_to do |format|
format.html { render 'posts/new' }
format.js
end
end
end
private
def post_params
params.require(:post).permit(:title, :content)
end
def get_all
@posts = Post.paginate(page: params[:page], per_page: 3)
end
end
index.html.erb:
<div class="form_wrapper">
<%= render 'posts/form_ajax' %>
</div>
<hr/>
<div class="result"><p></p></div>
<div class="posts_wrapper">
<%= render 'posts/post', posts: @posts %>
</div>
<% content_for :javascripts do %>
<%= javascript_include_tag 'index_page' %>
<% end %>
posts/_form_ajax.html.erb
<%= form_for(@post, remote: true) do |f| %>
<%= render "shared/form", f: f %>
<div>
<%= f.submit "Add" %>
</div>
<% if @post.errors.any? %>
<ul>
<% @post.errors.full_messages.each do |err| %>
<li><%= err %></li>
<% end %>
</ul>
<% end %>
<% end %>
posts/_post.html.erb
<%= will_paginate @posts, :params => {:action => 'index', :controller => 'posts' } %>
<% @posts.each do |p| %>
<div class="post">
<p>Title: <%= p.title %></p>
<p>Content: <%= p.content %></p>
<p>
<%= link_to "edit", edit_post_path(p) %>
<%= link_to p, method: :delete, data: { confirm: 'Are you sure?' }, remote: true do %>
<button>Delete</button>
<% end %>
</p>
</div>
<hr/>
<% end %>
posts/create.js.erb
$(".form_wrapper").html("<%= escape_javascript(render 'posts/form_ajax') %>");
$(".posts_wrapper").html("<%= escape_javascript(render 'posts/post', posts: @posts) %>");
Did you try turning off turbo-links? I noticed sometimes it doesn't jive with some javascript files gem file, application.js file get rid of //= require turbolinks in your application file & comment out the gem 'turbolinks' in your gem file , then rebundle
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.