Getting 500 internal server error with ajax/will_paginate in Rails - javascript

I've built a card slider where 20 cards are loaded on each page. I'm trying to have it so that when the user clicks on a button on the the last card (card with index 19), an AJAX call is made to render the next page and replace my original 20 cards with the next 20. I'm using the will_paginate gem and I can extract the correct href for the next page (i.e. http://localhost:3000/events/queued?page=2). But when I make a get request to it, the console shows the error "Failed to load resource: the server responded with a status of 500 (Internal Server Error)". I manually entered that url into my browser and that link works fine. I tried to follow along the RailsCast on will_paginate and ajax and modify it to suit my needs but I'm pretty sure I botched something along the way. Thanks in advance for any help!
index.html.erb
<% if #events %>
<div id="event_carousel" class="col-sm-10 col-sm-offset-1 owl-carousel">
<% #events.each do |event| %>
<%= render 'event', event: event %>
<% end %>
</div>
<!-- this is set to display none -->
<div class="text-center">
<h3><%= will_paginate #events %></h3>
</div>
<% end %>
event.js
var cardCounter = 0;
var cardOwlIndex = 0;
var linksArr = [];
$.ajaxSetup({'cache': true
});
$(function(){
var owl = $("#event_carousel");
links = $('.pagination > a');
for (var i = 0; i < links.length - 1; i++) {
linksArr.push(links[i].href);
};
$('.btn-square.like').off().on('click', function() {
$(this).toggleClass('btn-pressed-square-like');
owl.trigger('owl.next');
var owlIndex = $(this).closest('.owl-item').index();
alert(owlIndex);
cardCounter = owlIndex;
cardOwlIndex = owlIndex;
console.log(cardCounter);
if (cardCounter === 19 && cardOwlIndex === 19) {
alert(linksArr[0]);
$.get(linksArr[0], null, null, "script");
};
});
});
index.js.erb
$('#event_carousel').html("<%= escape_javascript(render partial: 'event') %>");
events_controller.rb
def index
#events = Event.with_rankings(current_user.id, Date.today, 1.month.from_now)
.order("event_rankings.weighted_score DESC")
.paginate(:page => params[:page], :per_page => 20)
respond_to do |format|
format.js
end
end
EDIT:
error logs:
ActionView::Template::Error (undefined local variable or method `event' for #<#<Class:0x007fcbd06fd850>:0x007fcbd553d740>):
1: <div class="col-sm-12">
2: <div class="col-sm-12 event-card flip" style="background-image: url(<%= event.image.url(:large) %>);" id="<%= event.id%>">
3: <div class="card">
4: <div class="card-face front">
5: <% if current_user && current_user.admin %>
app/views/events/_event.html.erb:2:in `_app_views_events__event_html_erb__2820478606869763483_70256714846000'
app/views/events/index.js.erb:1:in `_app_views_events_index_js_erb___681525537736992419_70256717102340'
app/controllers/events_controller.rb:55:in `queued'
DevTools shows that it's breaking on this line:
xhr.send( ( options.hasContent && options.data ) || null );

As you want to replace all of the current records with the new page results so you need to replace existing page content with the new one exactly like the index.html.erb
Here are steps to do it.
1.Create a common partial for your events.
_events.html.erb
<% if #events %>
<div id="event_carousel" class="col-sm-10 col-sm-offset-1 owl-carousel">
<% #events.each do |event| %>
<%= render 'event', event: event %>
<% end %>
</div>
<!-- this is set to display none -->
<div class="text-center">
<h3><%= will_paginate #events %></h3>
</div>
<% end %>
2.Now in your index.html.erb
<div id="events_container">
<%=render partial: 'events'%>
</div>
3.Now for your ajax request add following line index.js.erb
$('#events_container').html("<%= escape_javascript(render partial: 'events') %>");

Related

Hide Load More buttons when all items have been rendered in Ruby on Rails

I'm currently trying to implement the Load More button in Ruby on Rails. I've managed to implement it. However, the Load More button still appears even though there is no more photos left to be rendered.
Here are the lists of codes:
index.html.erb
<div class = 'container'>
<div class = 'section-header'>
<h2> Let's Rewind! </h2>
</div>
<div class='row'>
<div class = 'container'>
<div class='cust-cont'>
<%= render #scroll_photos %>
</div>
</div>
</div>
<div class="load-more-container">
<%= image_tag "ajax-loader.gif", style: "display:none;", class: "loading-gif" %>
<%= link_to "Load More", scroll_photos_path, class: "load-more" %>
</div>
</div>
_scroll_photo.html.erb
<div class="col-lg-12 col-md-4 col-xs-12">
<div class="image-box-4-3">
<div class="record" data-year="<%= scroll_photo.year %>">
<div class="image-content">
<%= image_tag(scroll_photo.image_link, width: "100%") %>
</div>
</div>
</div>
</div>
and the controller
if params[:year]
# get all records with id less than 'our last id'
# and limit the results to 5
#scroll_photos = ScrollPhoto.where('year < ?', params[:year]).limit(2)
else
#scroll_photos = ScrollPhoto.limit(2)
end
respond_to do |format|
format.html
format.js
end
the javascript
$(document).ready(function(){
// when the load more link is clicked
$('a.load-more').click(function(e){
// prevent the default click action
e.preventDefault();
// hide load more link
$('.load-more').hide();
// show loading gif
$('.loading-gif').show();
// get the last id and save it in a variable 'last-id'
var last_year = $('.record').last().attr('data-year');
// make an ajax call passing along our last user id
$.ajax({
// make a get request to the server
type: "GET",
// get the url from the href attribute of our link
url: $(this).attr('year'),
// send the last id to our rails app
data: { year: last_year },
// the response will be a script
dataType: "script",
// upon success
success: function(){
// hide the loading gif
$('.loading-gif').hide();
// show our load more link
$('.load-more').show();
}
});
});
});
index.js.erb
$('.cust-cont').append('<%= escape_javascript(render(:partial => #scroll_photos)) %>')
You can hide the load more part when the controller action return empty #scroll_photos
# in your javascript file
<% if #scroll_photos.empty? %>
$('.load-more-container').hide()
<% else %>
$('.cust-cont').append('<%= escape_javascript(render(:partial => #scroll_photos)) %>')
<% end %>

Ajax record delete not appended to HTML

I am venturing into AJAX and would like to delete a record of a model and followed this thread : How to perform Controller.destroy action asynchronously in rails?
models:
Photographe
Photographephoto
views/photographes/edit.html.erb
<div id="sectionimages" class="gutter-0 row" >
<% #photographe.photographephotos.all.each do |f| %>
<div class="col-md-2 col-sm-3 col-xs-6 col">
<%= link_to professionnel_photographe_photographephoto_path(#photographe.professionnel.id,#photographe.id, f.id), method: :delete, remote: 'true', id: "destruction"+f.id.to_s do %>
<div class="killimage" >
<%= image_tag f.image.url(:small) %>
<%= image_tag 'fatcrosswhite.svg', class: 'imgover' %>
</div>
<% end %>
</div>
<% end %>
</div>
link to Photographephotos#destroy is remote and there's an id like "destruction134"
photographephotos_controller.rb
def destroy
#imagedestroyed = Photographephoto.find(params[:id])
#imagedestroyedid = #imagedestroyed.id
#imagedestroyed.image = nil
#imagedestroyed.save
#imagedestroyed.destroy
respond_to do |format|
format.js
end
end
views/photographephotos/destroy.js.erb
var destroyelement = document.getElementById("<%= "destruction"+#imagedestroyedid.to_s %>");
destroyelement.parentNode.remove();
Problem is the file is indeed deleted but I have to refresh the page to see it removed. It seems the javascript is not effective. (I am trying to remove the parent of the link which is a Bootstrap DIV)

Change a partial with AJAX

I learn Ajax from some time, which is great by the way, so i'm not really an expert of it. So I need some advice about it.
I'm currently building a group system. I have a tab system to differentiate your own groups and the others. What I trying to do know, is script an ajax to send my partial group from a tab to the other. For example when the user quit a group, it will disappear of my groups to appear in the tab others.
I succeed the first step but I don't really know how I can send the form into the other tab.
As you can see bellow, I've try to send the id, but there is no partial form include. So it's just rendering the id of my group.
Any advices to include the partial (_group2.html.erb) ?
My code :
Index(group):
<div class="panel-body">
<div class="tab-content">
<div class="tab-pane fade in active" id="tab1default_group" style="padding:0px;">
<div class="group_area">
<% #my_groups.each do |group| %>
<div class="group_box<%=group.id%>">
<%= render 'group', group: group %>
</div>
<% end %>
</div>
</div>
<div class="tab-pane fade in" id="tab2default_group" style="padding:0px;">
<div class="group_area2">
<% #groups_out.each do |group| %>
<div class="group_box2<%=group.id%>">
<%= render 'group2', group: group %>
</div>
<% end %>
</div>
</div>
</div>
</div>
rem_req.js.erb(group):
$(".group_box<%=#group.id%>").fadeOut();
$(".group_area2").append('<%= render partial: #group2 %>');
Groups_controller :
def rem_req
if #group.groupes_admin.count == 1 && #group.groupes_admin.where(user_id: current_user).any?
flash[:error] = "Vous devez définir un nouvel Admin ou supprimer ce groupe"
else
RemReqGroupJob.perform_later(current_user, #group)
flash[:error] = "Vous ne faites plus parti de #{#group.name}"
#group2 = Group.where(id: #group.id).last
end
respond_to do |format|
format.html { redirect_back }
format.js
end
end
And when i try to run this, I have this error :
ActionView::Template::Error ('nil' is not an ActiveModel-compatible object. It must implement :to_partial_path.):
I assume the happy case scenario to give you direction. I think you are close but you need to make some tweak
From the snippet
<% #groups_out.each do |group| %>
<div class="group_box2<%=group.id%>">
<%= render 'group2', group: group %>
</div>
<% end %>
first move <div class="group_box2<%=group.id%>">..</div> also in group2 partial.
Then replace $(".group_area2").append('<%= render partial: #group2 %>');
with $(".group_area2").append('<%= j(render(partial: "group2")) %>');

Rails Kaminari example infinite scroll not working

I am trying to implement kaminari rails infinite scroll using this example.
It is working fine in my other apps but not working in this app.
Kaminari example
My company controller
def index
#companies = Company.all.page(params[:page]).per(4)
end
My index.html.erb
<div class="posts">
<div class="page">
<%= render #companies %>
</div>
</div>
<%= paginate #companies %>
My _company.html.erb
<div class="post">
<% company_decorator = CompanyDecorator.new(company)%>
<h4><%= company.name %> ||
No. of operations: <%= company_decorator.number_of_operations %> ||
Average Amount : <%= company_decorator.average_of_amount %> ||
Highest of Month: <%= company_decorator.highest_of_month%> ||
Accepted Operations: <%= company_decorator.accepted_operations%>
</h4>
<ul>
<% company.operations.each do |operation| %>
<li><%= operation.id%></li>
<%end%>
</ul>
</div>
My assets/javascripts/companies.js.coffee
$(document).ready ->
$(".posts .page").infinitescroll
navSelector: "nav.pagination"
nextSelector: "nav.pagination a[rel=next]"
itemSelector: ".posts .post"
My index.js.erb
$(".posts").append("<div class='page'><%= escape_javascript(render(#companies)) %></div>");
I am unable to find problem please help me. This same code is working in my other app.
Try
def index
#companies = Company.all.page(params[:page]).per(25)
end
playing with the pagination length.. I've heard that sometimes works

Rails: Checkbox to change the value of a variable on click

I have a basic to do type app and I am trying to change the variable completed for an item to the current date/time when I click a checkbox. I found this post, which has led me to the following code structure:
My lists#show, on which items are created, checked off (updated), edited, and deleted:
<div class="container">
<div class="row" style="height: 70px"></div>
</div>
<div class="col-xs-10 col-xs-push-1 container">
<div class="md-well">
<h1 class="text-center"><%= #list.name %></h1>
<% if #items.count == 0 %>
<h4 class="text-center">You don't have any items on this list yet! Want to add some?<h4>
<% elsif #items.count == 1 %>
<h4 class="text-center">Only <%= #items.count %> Item To Go!</h4>
<% else %>
<h4 class="text-center">You Have <%= #items.count %> Items To Go!</h4>
<% end %>
<%= render 'items/form' %>
<% #items.each do |item|%>
<p>
<%= form_for [#list, item], class: "inline-block", id: 'item<%= item.id %>' do |f| %>
<%= f.check_box :completed, :onclick => "$this.parent.submit()" %>
<% end %>
<%= item.name %>
( <%= link_to "Delete", list_item_path(#list, item), method: :delete %> )
</p>
<% end %>
<div class="text-center">
<%= link_to "Back to My Lists", lists_path %>
</div> <!-- text-center -->
</div> <!-- well -->
</div> <!-- container -->
Here is my update method in my items_controller (which I believe has jurisdiction instead of the lists_controller even though it is the lists#show page because it is an item being updated:
def update
#list = List.friendly.find(params[:list_id])
#item = #list.items.find(params[:id])
#item.name = params[:item][:name]
#item.delegated_to = params[:item][:delegated_to]
#item.days_til_expire = params[:item][:days_til_expire]
#item.completed = params[:item][:completed]
#item.user = current_user
if #item.update_attributes(params[:item])
#item.completed = Time.now
end
if #item.save
flash[:notice] = "List was updated successfully."
redirect_to #list
else
flash.now[:alert] = "Error saving list. Please try again."
render :edit
end
end
Here is what is currently appearing:
And here are the two problems I'm having:
LESS IMPORTANT PROBLEM: The checkboxes should be displayed inline with the list items but aren't. My class inline-block simply makes links to this in the application.scss file:
.inline-block {
display: inline-block !important;
}
MORE IMPORTANT PROBLEM: Even after the checkbox is clicked, the value for completed remains nil as per my console:
[6] pry(main)> Item.where(name: "Feed Dexter")
Item Load (0.1ms) SELECT "items".* FROM "items" WHERE "items"."name" = ? [["name", "Feed Dexter"]]
=> [#]
Any ideas how to make this functional?

Categories

Resources