Infinite scrolling in rails with haml - ruby-on-rails-3

I'm trying to implement infinite scrolling into my project.
I have do everything as in this howto: https://github.com/amatsuda/kaminari/wiki/How-To:-Create-Infinite-Scrolling-with-jQuery
But it's not working for me :(
Controller:
def show
category = Category.find(params[:id])
products = category.products.page(params[:page])
#category = CategoryDecorator.decorate(category)
#products = ProductDecorator.decorate_collection(products)
respond_to do |format|
format.js
format.html
format.xml { render :xml => #products }
end
end
show.html.haml:
#products_list
%page
= render 'products_list'
:javascript
$(function() {
var page = 1,
loading = false;
function nearBottomOfPage() {
return $(window).scrollTop() > $(document).height() - $(window).height() - 200;
}
$(window).scroll(function(){
if (loading) {
return;
}
if(nearBottomOfPage()) {
loading=true;
page++;
$.ajax({
url: '/universes/nautique/sports/surfwear/categories/boarshorts?per_page=' + page,
type: 'get',
dataType: 'script',
success: function() {
$(window).sausage('draw');
loading=false;
}
});
}
});
$(window).sausage();
}());
- content_for :javascript do
= javascript_include_tag "jquery.sausage"
Partial _products_list.html.haml:
- #products.each_with_index do |product,index|
.block-prodlist{ data: { index: product.id } }
.inner.onfocus
.selection
%label AJOUTER À MA SÉLECTION
%input.chk{:name => "", :type => "checkbox", :value => ""}/
.thumbproduit
= index
%img{:alt => "Produit", :height => "194", :src => "/assets/editorial/produit1.jpg", :width => "194"}/
.prixcaption -20%
.context
%h3
= product.brand_name
And show.js.haml:
$("#products_list").append("#{escape_javascript(render(#products))}");
I don't see show.js in my firebug.

Error was with store script - show.js.haml
I have change #products to my partial name:
$("#products_list").append("#{escape_javascript(render('products_list'))}");

Related

Kendo UI Grid CRUD firing multiple times

I have a kendo UI grid in my page. Below is the code of kendo UI grid with CRUD datasource actions.
#(Html.Kendo().Grid<Gts.GlaspacLX.Web.ViewModel.ProductViewModel>()
.Name("xyzGrid")
.Columns(columns =>
{
columns.Bound(p => p.SelectedProductCategory).EditorTemplateName("_ProductDropDownList").Title("Product Category").HtmlAttributes(new { #tabindex = "8" });
columns.Bound(p => p.Name).Width(130).Title("% Off").HtmlAttributes(new { #tabindex ="9" });
columns.Bound(p => p.Rate).Width(130).HtmlAttributes(new { #class = "prodDiscRtAlign",#tabindex= "10" });
columns.Bound(p => p.Hours).Width(130).HtmlAttributes(new { #class = "prodDiscRtAlign",#tabindex= "11" });
if (SiteContext.CurrentUser.HasPrivilege(PrivilegeNames.Maintenance, PermissionNames.DELETE))
{
columns.Command(command => { command.Destroy(); }).Width(110).Title("Delete").HtmlAttributes(new { #tabindex = "12" });
}
})
.ToolBar(commands =>
{
commands.Create();
commands.Save();
})
.Editable(editable => editable.Mode(GridEditMode.InCell).CreateAt(GridInsertRowPosition.Bottom))
.Sortable()
.Navigatable()
.DataSource(dataSource => dataSource
.Ajax()
.Batch(true)
.ServerOperation(false)
.Model(model =>
{
model.Id(p => p.ProductID);
model.Field(p => p.SelectedProductCategory).DefaultValue(ViewBag.DefaultProductCategory);
})
.Read(read => read.Action("Product_Read", "ProductController"))
.Update(update => update.Action("Product_Update", " ProductController "))
.Create(create => create.Action("Product_Create", " ProductController "))
.Destroy(update => update.Action("Product_Destroy", " ProductController ")
))
.Events(e => e.Edit("proField").DataBound("boundProductChange"))
)
Below is the screen shot of "Save" button just after the kendo grid. It's responsible for any create/update operation of the page.
My problem is once I clicked on Save button for any create or update operation its posting the action method twice. You can see the console of above screen shot.
Below is the piece of the code of my controller's action method:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Product_Create([DataSourceRequest] DataSourceRequest request, [Bind(Prefix = "models")]IEnumerable<ProductViewModel> product){
return Json(results.ToDataSourceResult(request, ModelState));
}
Below is proField function code :-
function proField(e) {
var defaultproduct = $("#DefaultProductCategory").val();
defaultproduct = "\n" + defaultproduct + "select ";
if (e.model.SelectedProductCategory == "Default" && (e.sender._editContainer[0].textContent == defaultproduct || e.sender._editContainer[0].textContent == "\n select ")) {
e.sender._editContainer[0].disabled = true;
e.sender._editContainer[0].children[0].textContent = "Default";
e.sender.table[0].rows[1].cells[1].click();
e.sender.table[0].rows[1].cells[4].disabled = true;
}
}
after insert any record you should return primary(Id) key to view.
see kendo demo.

How to call helper method through select_tag

I am trying to call helper method from select_tag. I tried this:
<%= select_tag(:themes, options_for_select({"Black" => "compiled/styles", "Green" => "compiled/styles2"})) %>
When I put alert(this.options[this.selectedIndex].value) instead of calling method, it works. How can I change my code to call the method as desired?
EDIT
I have this on my application.js
$(document).ready(function() {
$('#display_themes').change(function(){
$.ajax({url: '<%= url_for :controller => 'application', :action => 'set_themes()', :id => 'this.value' %>',
data: 'selected=' + this.value,
dataType: 'script'
})
})
});
And in controller I have set_themes methode
def set_themes()
#themes = params[:id]
respond_to do |format|
redirect_to '/galleries'
format.html # index.html.erb
format.xml { render :xml => #themes }
end
end
The problem now is #themes still empty even I change the dropdown
Routes.rb
match '', :controller => 'application', :action => 'set_themes()'
To route to application#set_themes:
match '/set_themes', to: 'application#set_themes', as: :set_themes
With that done, just direct the url in ajax as follows:
$.ajax({url: "<%= set_themes_path %>",
It should be #themes = params[:selected] in your controller based on what you are trying to do in application.js.

Rails 3 : In submit button :disable_with is not working

In this following code :disable_with is not working in rails 3. But it is perfectly working in rails 2.2
What is wrong in this code?
<%= submit_tag "Save", :class => "buttons",
:disable_with => "Processing",
:id => 'save_btn' %>
Since version 3.2.5 you should not use :disable_with.
<%= submit_tag "Save", 'data-disable-with' => "Processing", :class => "buttons", :id => 'save_btn' %>
or
<%= submit_tag "Save", data: { disable_with: "Processing" }, :class => "buttons", :id => 'save_btn' %>
Check the following in your raw html:
the submit button has data-disable-with attribute
your page includes jQuery js. For me I have:
https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js
you page includes jquery_ujs js. For me I have:
/javascripts/jquery_ujs.js
You can read more on https://github.com/rails/jquery-ujs. Different installations for different rails versions.
I had a similar issue on Safari 8.0.6 and latest rails-ujs. Here's my approach of solving this issue:
%button{ class: 'btn btn-action js-submit', data: { method: :put, 'href' => '...', disable_with: "<i class='icon icon-spinner icon-spin'></i>".html_safe }} Submit
$('.js-select-plan').click(function(event) {
event.preventDefault();
var $target = $(this),
href = $target.data('href'),
method = $target.data('method'),
formTarget = $target.attr('target'),
csrfToken = $('meta[name=csrf-token]').attr('content'),
csrfParam = $('meta[name=csrf-param]').attr('content'),
form = $('<form method="post" action="' + href + '"></form>'),
metaData = '<input name="_method" value="' + method + '" type="hidden" />';
if (csrfParam !== undefined && csrfToken !== undefined) {
metaData += '<input name="' + csrfParam + '" value="' + csrfToken + '" type="hidden" />';
}
if (formTarget) {
form.attr('target', formTarget);
}
// disable button/link element
var contentMethod = $target.is('button') ? 'html' : 'val';
var replacement = $target.data('disable-with');
$target.data('ujs:enable-with', $target[contentMethod]());
if (replacement !== undefined) {
$target[contentMethod](replacement);
}
$target.prop('disabled', true);
form.hide().append(metaData).appendTo('body');
setTimeout(function(){
form.submit();
}, 50);
});
This works like a charm in all browsers. For better flexibility you might want to wrap this in a helper.

gmaps4rails having trouble rendering custom marker images

I have 4 types of markers on my map and I am loading an image for each point depending on it's "school type". This is working fine but I'm getting a weird artifact on the map that I don't get when using the standard marker image.
def map
#json = School.where(:disabled => [false, nil]).to_gmaps4rails do |school, marker|
marker.infowindow render_to_string(:partial => "schools/marker", :locals => { :object => school })
if school.school_type_id == 1
marker.picture({ "picture" => view_context.image_path('map_icons/blue_P.png'),"width" => '20',"height" => '34'})
elsif school.school_type_id == 2
marker.picture({ "picture" => view_context.image_path('map_icons/red_C.png'),"width" => '20',"height" => '34'})
elsif school.school_type_id == 3
marker.picture({ "picture" => view_context.image_path('map_icons/yellow_J.png'),"width" => '20',"height" => '34'})
elsif school.school_type_id == 4
marker.picture({ "picture" => view_context.image_path('map_icons/green_I.png'),"width" => '20',"height" => '34'})
end
marker.json({ :id => school.id })
end
respond_to do |format|
format.html # index.html.erb
format.json { render json: #schools }
end
end
Images of the artifact:
http://foa-approved.org/map_artifact1.png
http://foa-approved.org/map_artifact2.png
I am using the css fix for the map controls:
.map_container img {
max-width: none;
}
Can this fix work on the marker image or it is something else entirely?

Rails - Clean way of calling model method in respond_to differently depending on the format

I have some code like this:
respond_to do |format|
format.html { #all_activities = current_user.recent_activities(#size_per_page,params[:start],nil) }
format.csv { #all_activities = current_user.recent_activities(nil,params[:start],nil); build_activity_csv }
format.xls { #all_activities = current_user.recent_activities(nil,params[:start],nil);
send_data(build_excel_all, :filename => "#{Time.now.strftime('%Y-%m-%d')}_Activity_All.xls", :type => "application/xls", :disposition => 'attachment')
}
format.js { #all_activities = current_user.recent_activities(#size_per_page,params[:start],nil) }
format.pdf { #all_activities = current_user.recent_activities(nil,params[:start],nil); prawnto :filename => "#{Time.now.strftime('%Y-%m-%d')}_Activity_All", :inline => false
}
end
As you see, I am calling the same method in the different formats, but in some cases I use the #size_per_page variable, and sometimes I call the method with nil instead.
Anyone recommend a better, cleaner or non repeating way of doing this?
Thanks
I'd separate that call into a function but that's just me.
Here's how I would do it:
respond_to do |format|
format.html { set_all_activities(#size_per_page) }
format.js { set_all_activities(#size_per_page) }
format.csv do
set_all_activities(nil)
build_activity_csv
end
format.xls do
set_all_activities(nil)
send_data(
build_excel_all,
:filename => "#{Time.now.strftime('%Y-%m-%d')}_Activity_All.xls",
:type => "application/xls",
:disposition => 'attachment')
end
format.pdf do
set_all_activities(nil)
prawnto(
:filename => "#{Time.now.strftime('%Y-%m-%d')}_Activity_All",
:inline => false)
end
end
def set_all_activities(size)
#all_activities = current_user.recent_activities(size, params[:start], nil)
end
I'm assuming params[:start] and the last nil argument are consistent, right?