Drag and drop ordering in rails
Add order_number column into news table:-
rails g migration add_order_number_to_news order_number:integer
In config/routes.rb
get '/news_ordering/(:id)' => 'news#news_ordering', as: :news_ordering
rails g migration add_order_number_to_news order_number:integer
In config/routes.rb
get '/news_ordering/(:id)' => 'news#news_ordering', as: :news_ordering
post '/re_order_news' => 'news#re_order_news'
In app/views/news/news_ordering.html.erb
<style>
#sortable {
list-style-type: none;
margin: 0;
width: 60%;
cursor: pointer;
}
.pic_box {
border: 1px #cccccc solid;
padding: 2%;
margin: 1%;
width: 50%;
}
.img_box{
height: 60px;
width: 60px;
}
</style>
<div class="wrapper wrapper-content animated fadeInRight">
<p id="notice"><%= notice %></p>
<div class="row">
<div class="col-lg-12">
<div class="ibox float-e-margins">
<div class="ibox-content">
<div class="alert alert-success" id="alert_div" style="display:none">
<button onclick="hide_alert()" class="close">×</button>
<span id="response_message"></span>
</div>
<h2>Please drag & drop re-order them.</h2><br>
<ul id="sortable">
<% @news.each do |news| %>
<li class="pic_box" id='news_<%= "#{news.id}" %>'>
<%= news.title %>
</li>
<% end %>
</ul>
</div>
</div>
</div>
</div>
</div>
<!-- Content for Javascript -->
<% content_for :javascript do %>
<script type="text/javascript">
function hide_alert(){
$("#alert_div").fadeOut("slow");
};
$(function() {
$( "#sortable" ).sortable({
update: function(event, ui) {
var inputTypes = [];
$('#sortable li').each(function(){
inputTypes.push($(this).attr('id'));
});
$.ajax({
url: "/re_order_news.json",
type: 'POST',
data: {ids_array: inputTypes},
success: function(response){
$("#response_message").html(response.msg);
$("#alert_div").fadeIn("slow");
}
});
}
}).disableSelection();
// $( "#sortable" ).disableSelection();
});
</script>
<% end %>
In app/news_controller.rb
class NewsController < ApplicationController
def news_ordering
@news = News.all
end
def re_order_news
status = "News order changed successfully."
ids = params[:ids_array]
ids.each_with_index do |id, index|
news = News.find_by_id(id.split("_").last)
if news.present?
news.update_attributes(order_number: index)
end
end
respond_to do |format|
format.json { render json:{msg: status} }
end
end
end
Comments
Post a Comment