Changing dropdown menu based on another dropdown in Ruby on Rails - javascript

Currently I have a form that looks like :
<tr>
<td>
<%= f.hidden_field :_destroy %>
<%= link_to "remove", '#', class: "remove_record"
</td>
<td><%= f.date_field :date, as: :date, value: f.object.try(:strftime,"%m/%d/%Y"), class: 'form-control' %> </td>
<td><%= f.text_field :description, label: false, class: 'form-control input' %></td>
<td><%= f.text_field :reference, label: false, class: 'form-control input' %></td>
<td> <%= f.collection_select :bank_account_id, BankAccount.all, :id, :name, {:prompt => false},class:"btn btn-sm" %></td>
<td><%= f.collection_select :gl_account_id, GlAccount.all, :id, :name, {:prompt => false},class:"btn btn-sm" %></td>
<td><%= f.collection_select :vat_type, Transaction.vat_types.map{ |dp| [dp.first, dp.first.humanize] }, :first, :second,{:prompt => false},class:"btn btn-sm" %></td>
<td> <%= f.text_field :total_amount, class: 'form-control input' %></td>
<% f.check_box :payment, :value => true %>
</table>
I want to add another <td> after my remove column that prompts a user to select what type of payment it is:
<select>
<option value="regular">Regular</option>
<option value="invoice">Invoice</option>
</select>
This would change the row:
<td><%= f.collection_select :gl_account_id, GlAccount.all, :id, :name, {:prompt => false},class:"btn btn-sm" %></td>
And will become:
<td><%= f.collection_select :purchase_id, Purchase.all, :id, :invoice_number, {:prompt => false},class:"btn btn-sm" %></td>
This way - the user can easily change the type of transaction they are performing without having to be redirect to a new form. Any ideas on how I can achieve this?

1 => Add a select option for transaction type after remove link
<%=select_tag "transaction_type", options_for_select([['regular', 'Regular'], ['invoice', 'Invoice']]), class: 'transaction_type'%>
2 => Add a unique id on select_field which will be triggered dynamically on change of transaction type
<td><%= f.collection_select :gl_account_id, GlAccount.all, :id, :name, {:prompt => false},class:"btn btn-sm", id: 'gl_account' %></td>
<td><%= f.collection_select :vat_type, Transaction.vat_types.map{ |dp| [dp.first, dp.first.humanize] }, :first, :second,{:prompt => false},class:"btn btn-sm", id: "vat_type" %></td>
3 => Using Jquery
<script>
//by default hide both gl_account and vat_type select box
$('#vat_type, #gl_account').hide();
// on change transaction_type show/hide these select box
$('.transaction_type').on('change', function(){
var transaction_type_Val = $(this).val();
if (transaction_type_Val == 'regular'){
$('#gl_account').show();
$('#vat_type').hide();
}else{
$('#gl_account').hide();
$('#vat_type').show();
}
})
</script>

Related

Different jQuery/JS errors in rails app with bootsrap

I have a filter that filters my form. When I open it my datepicker does not work even if the same code works on another page of the app. I do not get the error on the other pages.
Uncaught TypeError: $(...).datepicker is not a function
On every page I get
DEPRECATED: This filename doesn't follow the convention, use bootstrap-datepicker.en-CA.js instead.
$.fn.datepicker.deprecated # core.self-c808be6e04274a80c551034d8f8a677b7c3995aec044ea4e6edf9cbbc19ff750.js?body=1:2012
(anonymous) # bootstrap-datepicker-en-CA.self-fb416403a677f41efad9cfc05939c9fe3eeb04627845d85da10d9eee99ba96b2.js?body=1:21
(anonymous) # bootstrap-datepicker-en-CA.self-fb416403a677f41efad9cfc05939c9fe3eeb04627845d85da10d9eee99ba96b2.js?body=1:23
core.self-c808be6e04274a80c551034d8f8a677b7c3995aec044ea4e6edf9cbbc19ff750.js?body=1:2012 DEPRECATED: The language code "kh" is deprecated and will be removed in 2.0. For Khmer support use "km" instead.
$.fn.datepicker.deprecated # core.self-c808be6e04274a80c551034d8f8a677b7c3995aec044ea4e6edf9cbbc19ff750.js?body=1:2012
(anonymous) # bootstrap-datepicker.kh.self-6562a5a87f529e9a3121f8b49f20a6f7d3651340738f7d747a2418d721d01eae.js?body=1:21
(anonymous) # bootstrap-datepicker.kh.self-6562a5a87f529e9a3121f8b49f20a6f7d3651340738f7d747a2418d721d01eae.js?body=1:22
core.self-c808be6e04274a80c551034d8f8a677b7c3995aec044ea4e6edf9cbbc19ff750.js?body=1:2012 DEPRECATED: The language code "kr" is deprecated and will be removed in 2.0. For korean support use "ko" instead.
$.fn.datepicker.deprecated # core.self-c808be6e04274a80c551034d8f8a677b7c3995aec044ea4e6edf9cbbc19ff750.js?body=1:2012
(anonymous) # bootstrap-datepicker.kr.self-ca28b775db5a32ebbee6667b0bc40e26e078ce363db5c55c9a904155d3b9fdb5.js?body=1:19
(anonymous) # bootstrap-datepicker.kr.self-ca28b775db5a32ebbee6667b0bc40e26e078ce363db5c55c9a904155d3b9fdb5.js?body=1:20
core.self-c808be6e04274a80c551034d8f8a677b7c3995aec044ea4e6edf9cbbc19ff750.js?body=1:2012 DEPRECATED: This language code "rs-latin" is deprecated (invalid serbian language code) and will be removed in 2.0. For Serbian latin support use "sr-latin" instead.
$.fn.datepicker.deprecated # core.self-c808be6e04274a80c551034d8f8a677b7c3995aec044ea4e6edf9cbbc19ff750.js?body=1:2012
(anonymous) # bootstrap-datepicker.rs-latin.self-a3302a16cb7cc00b6d455f26ed8a73f8890da7280ee9507c2cd9fe9f36ec6352.js?body=1:20
(anonymous) # bootstrap-datepicker.rs-latin.self-a3302a16cb7cc00b6d455f26ed8a73f8890da7280ee9507c2cd9fe9f36ec6352.js?body=1:21
core.self-c808be6e04274a80c551034d8f8a677b7c3995aec044ea4e6edf9cbbc19ff750.js?body=1:2012 DEPRECATED: This language code "rs" is deprecated (invalid serbian language code) and will be removed in 2.0. For Serbian support use "sr" instead.
Uncaught TypeError: $(...).popover is not a function
at HTMLDocument.<anonymous> (bootstrap.self-fdc98dee79ee88255e10cac6caa91338165cb76cf0d263744d8d90011fc2ef8f.js?body=1:3)
at fire (jquery.self-bd7ddd393353a8d2480a622e80342adf488fb6006d667e8b42e4c0073393abee.js?body=1:3233)
at Object.fireWith [as resolveWith] (jquery.self-bd7ddd393353a8d2480a622e80342adf488fb6006d667e8b42e4c0073393abee.js?body=1:3363)
at Function.ready (jquery.self-bd7ddd393353a8d2480a622e80342adf488fb6006d667e8b42e4c0073393abee.js?body=1:3583)
at HTMLDocument.completed (jquery.self-bd7ddd393353a8d2480a622e80342adf488fb6006d667e8b42e4c0073393abee.js?body=1:3618)
and I googled that this comes from importing jQuery twice. But my
application.js
//= require jquery
//= require rails-ujs
//= require activestorage
//= require bootstrap
//= require bootstrap-datepicker
//= require bootstrap/dropdown
//= require turbolinks
//= require_tree .
imports it just once and even the order should be ok.
html.erb
<script src="http://code.jquery.com/jquery-1.12.0.min.js"></script>
<%= csrf_meta_tags %>
<% provide(:title, "Mitarbeiter hinzufügen") %>
<div class="row">
<div class="col-md-6 col-md-offset-3">
<div>
<%= form_for :anything, url: add_worker_tm_trainings_path do |f| %>
<%= f.label :schicht %>
<%= f.collection_select :shift, Shift.all, :id, :name, include_blank: :true %>
<div class="lineshow">
<%= f.label :linie %>
<%= f.collection_select :line, Line.all, :id, :name, include_blank: :true %>
<%= f.submit "submit", :class => 'submit_button' %>
<% end %>
</div>
<div class="realform">
<%= form_with model: Trainingsmembership, url: add_worker_tm_trainings_path do |f| %>
<div style="overflow: auto; height: 350px">
<table>
<tr>
<th style="width: 25px"></th>
<th style="width: 200px"><%= sort_link "name" %></th>
<th style="width: 125px"><%= sort_link "position" %></th>
<th style="width: 75px"><%= sort_link "Schicht" %></th>
<th style="width: 100px"><%= sort_link "linie" %></th>
</tr>
<% #workers.each do |worker| %>
<tr>
<td><%= check_box_tag "worker_ids[worker_ids][]", worker.id %></td>
<td><%= worker.name %></td>
<td><%= Position.find(worker.position_id).name %></td>
<td><%= Shift.find(worker.shift_id).name %></td>
<td><% worker.line_ids.each do |line| %>
<%= Line.find(line).name %>
<% end %></td>
</tr>
<% end %>
</table>
</div>
<div style="overflow: auto; height: 350px">
<table>
<tr>
<th style="width: 25px"></th>
<th style="width: 200px"><%= sort_link "Training" %></th>
<th style="width: 100px"><%= sort_link "linie" %></th>
</tr>
<% #trainingall.each do |training| %>
<tr>
<td><%= check_box_tag "training_ids[training_ids][]", training.id %></td>
<td><%= training.name %></td>
<td><%= Line.find(training.where_lines).name %></td>
</tr>
<% end %>
</table>
</div>
<br><br>
<%= f.label "Gültigkeit" %>
<%= f.text_field :duration%>
<%= f.label "Prüfungstermin" %>
<%= f.text_field :date%>
<%= f.label "Bemerkung" %>
<%= f.text_field :comment%>
<%= f.label "PDF-Protokoll" %>
<%= f.text_field :attachement%>
<%= f.submit "Submit" %>
<!-- %= f.input :training_id, collection: #trainings, label_method: :name, value_method: :id, label: 'Training:', include_blank: false %>
%= f.input :duration, label: 'Gültigkeit:' %>
%= f.input :date, :as => :string, :input_html => { data: {behaviour: "datepicker"}}, label: 'Prüfungstermin:' %>
%= f.input :comment, as: :text, label: 'Bemerkung:' %>
%= f.input :attachement, as: :file, label: 'PDF-Protokoll:' %>
%= f.submit "Training bearbeiten", class: "btn btn-primary" %-->
<!--#%= f.input :worker_id, collection: Worker.all, label_method: :name, value_method: :id, label: 'Mitarbeiter', include_blank: false, input_html: { multiple: false } %>-->
<% end %>
</div>
<script type="text/javascript">
$(document).ready(function(){
$('.lineshow').hide();
$('.realform').hide();
$('#anything_shift').change(function () {
if($('#anything_shift option:selected').text != ""){
$('.lineshow').show();
}
});
$('#anything_line').change(function () {
if($('#anything_line option:selected').text != ""){
$('.realform').show();
}
});
$("submit").click(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "/trainings/add_worker_tm",
data: {
id: $(this).val(),
access_token: $("access_token").val()
},
success: function (result) {
$('.realform').show();
}
})
})
});
</script>
<script type="text/javascript">
$('#micropost_picture').bind('change', function() {
var size_in_megabytes = this.files[0].size/1024/1024;
if (size_in_megabytes > 5) {
alert('Maximum file size is 5MB. Please choose a smaller file.');
}
});
</script>
<script type="text/javascript">
$('[data-behaviour~=datepicker]').datepicker({
"format": "dd.mm.yyyy",
"weekStart": 1,
"autoclose": true
});
</script>
</div>
</div>
</div>
The ajax call is not working as well but I had not invested much time in it yet. I do not like the first line there but without my jQuery seems not working, but why? I think I included jQuery in my application.js...
controller.erb
def add_worker_tm
if !params.has_key?(:anything)
puts "emoty"
#worker = Worker.new
#workers = Worker.order("#{sort_column} #{sort_direction}")
#workerall = Worker.all
#trainings = Training.all
#trainingall = Training.all
else
#shift = params[:anything].require(:shift)
#line = params[:anything].require(:line)
#worker = Worker.new
#workersshifts = Worker.all.where("shift_id= ?", #shift)
puts #workersshifts
#workers = []
#workersshifts.each do |w|
puts w.line_ids
if w.line_ids.include? #line
#workers << w
end
end
#workerall = Worker.all
#trainings = Training.all.where(where_lines: #line)
#trainingall = Training.all.where(where_lines: #line)
end
end
def add_worker_tm
if !params.has_key?(:anything)
puts "empty"
#worker = Worker.new
#workers = Worker.order("#{sort_column} #{sort_direction}")
#workerall = Worker.all
#trainings = Training.all
#trainingall = Training.all
else
#shift = params[:anything].require(:shift)
#line = params[:anything].require(:line)
#worker = Worker.new
#workersshifts = Worker.where(shift_id: #shift)
#workers = []
#workersshifts.each do |w|
if !w.line_ids.include?(#line)
#workers << w
end
end
#workerall = Worker.all
#trainings = Training.all.where(where_lines: #line)
#trainingall = Training.all.where(where_lines: #line)
end
end
My controller is fine I think, I fixed my filter bug and it displays what I want.
Now my questions:
How can I fix the bootstrap js/jQuery errors?
How can I make the datepicker working again?
What do I need to change, that my AJAX call works correctly and displays my filtered tables without any refresh?
I am very confused and should add that I am very new to rails, jQuery and js.
After many hours try and error, I found some solutions.
I found out that turbolinks are evil and do not trigger all my events. After I found out, I deleted <script src="http://code.jquery.com/jquery-1.12.0.min.js"></script> and changed my script to
<script type="text/javascript">
document.addEventListener("turbolinks:load", function () {
$('.lineshow').hide();
$('.realform').hide();
Now it is working.
My datepicker seems like not working cause of my previous jQuery-Script so I made it to a simple_form_for and the picker is there again. I put the whole form in a partial.
<div>
<%= form_for :anything, :html=>{:id=>"filter", :multipart => true,:remote=>true}, url: add_worker_tm_trainings_path do |f| %>
<%= f.label :schicht %>
<%= f.collection_select :shift, Shift.all, :id, :name, include_blank: :true %>
<div class="lineshow">
<%= f.label :linie %>
<%= f.collection_select :line, Line.all, :id, :name, include_blank: :true %>
<%= hidden_field_tag :authenticity_token, form_authenticity_token %>
<%= f.submit "filter", {:class => "bttn-and-txt", :id => "filter", :name => "filter", :value => "filter"} %>
<% end %>
</div>
<div class="realform">
<%= simple_form_for(Trainingsmembership.new, url: add_worker_tm_trainings_path) do |f| %>
<div style="overflow: auto; height: 350px">
<table>
<tr>
<th style="width: 25px"></th>
<th style="width: 200px"><%= sort_link "name" %></th>
<th style="width: 125px"><%= sort_link "position" %></th>
<th style="width: 75px"><%= sort_link "Schicht" %></th>
<th style="width: 100px"><%= sort_link "linie" %></th>
</tr>
<% #workers.each do |worker| %>
<tr>
<td><%= check_box_tag "worker_ids[worker_ids][]", worker.id %></td>
<td><%= worker.name %></td>
<td><%= Position.find(worker.position_id).name %></td>
<td><%= Shift.find(worker.shift_id).name %></td>
<td>
<% worker.line_ids.each do |line| %>
<%= Line.find(line).name %>
<% end %></td>
</tr>
<% end %>
</table>
</div>
<div style="overflow: auto; height: 350px">
<table>
<tr>
<th style="width: 25px"></th>
<th style="width: 200px"><%= sort_link "Training" %></th>
<th style="width: 100px"><%= sort_link "linie" %></th>
</tr>
<% #trainingall.each do |training| %>
<tr>
<td><%= check_box_tag "training_ids[training_ids][]", training.id %></td>
<td><%= training.name %></td>
<td><%= Line.find(training.where_lines).name %></td>
</tr>
<% end %>
</table>
</div>
<br><br>
<%= f.input :duration, label: 'Gültigkeit:' %>
<%= f.input :date, :as => :string, :input_html => { data: {behaviour: "datepicker"}}, label: 'Prüfungstermin:' %>
<%= f.input :comment, as: :text, label: 'Bemerkung:' %>
<%= f.input :attachement, as: :file, label: 'PDF-Protokoll:' %>
<%= hidden_field_tag :authenticity_token, form_authenticity_token %>
<%= f.submit "Mitarbeiter hinzufügen", {:class => "btn btn-primary", :name => "submit", :value => "submit"} %>
<% end %>
</div>
<script type="text/javascript">
$('[data-behaviour~=datepicker]').datepicker({
"format": "dd.mm.yyyy",
"weekStart": 1,
"autoclose": true
});
</script>
<script type="text/javascript">
function GetCookie(name) {
var arg=name+"=";
var alen=arg.length;
var clen=document.cookie.length;
var i=0;
while (i<clen) {
var j=i+alen;
if (document.cookie.substring(i,j)==arg)
return "here";
i=document.cookie.indexOf(" ",i)+1;
if (i==0)
break;
}
return null;
};
document.addEventListener("turbolinks:load", function () {
$('.lineshow').hide();
//$('.realform').hide();
var visit=GetCookie("COOKIE1");
if (visit==null){
$('.realform').hide();
}
var expire=new Date();
expire=new Date(expire.getTime()+(5*60*1000));
document.cookie="COOKIE1=here; expires="+expire;
$('#anything_shift').change(function () {
if ($('#anything_shift option:selected').text != "") {
$('.lineshow').show();
}
});
$('#anything_line').change(function () {
if ($('#anything_line option:selected').text != "") {
$("#filter").click();
}
});
});
</script>
<script type="text/javascript">
$('#micropost_picture').bind('change', function () {
var size_in_megabytes = this.files[0].size / 1024 / 1024;
if (size_in_megabytes > 5) {
alert('Maximum file size is 5MB. Please choose a smaller file.');
}
});
</script>
</div>
With these javascripts and form.js.erb $("#filter").html("<%= j(render 'tform').html_safe %>") and in my controller I needed to add this before the end of the methods
respond_to do |format|
format.js { render 'trainings/add_worker_tm'}
format.html
end
everything looks like working. The cookies are a dirty solution to make it possible that a different request to the filter will be shown immediately.

How can use onclick on different table td in jquery?

I have one looping Dates and table content.
I want to display table content based on Dates. How's it possible please help me.
index.html.erb
<% #batches.each do |batch| %>
<tr>
**<td class = "pie" id ="demo"> <i class="fa fa-plus-circle"></i>
<%= batch.date.strftime("%Y-%m-%d") if !batch.date.nil? %></td>**
<td><%= batch.purchase_center.name.to_s if !batch.purchase_center.nil? %></td>
<td><%= batch.plant.name.to_s if !batch.plant.nil?%></td>
<td><%= batch.species.name.to_s if !batch.species.nil? %></td>
<td><%= batch.batch_number %></td>
<td><%= batch.total_quantity %></td>
<td><%= batch.calculated_yeild %></td>
<td><%= link_to '<i class="fa fa-users"></i>'.html_safe, "#", :class => "addsupplier", :id => "#{batch.serial_id}" %></td><td><%= link_to '<i class="fa fa-trash-o"></i>'.html_safe, batch, method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>
<tr class="<%= batch.serial_id %>" style="display:none">
<%= render :partial => "batch_counts/form", locals: {id: "#{batch.serial_id}"} %>
</tr>
**<td id ="two" style="display:">
Microsoft Corporation
Microsoft Corporation
</td>**
<% end %>
<script type="text/javascript">
$('#demo').click(function(){
$('#two').toggle();
});
</script>
I highlighted with star marks i.e. id = demo and id =two.
i have different dates and different message. So i want to display it on which date is having which message.
Based on dates display message.
Give a common class to each of them. Say, date-alert:
<td class="pie date-alert" id="demo"> <i class="fa fa-plus-circle"></i>
<%= batch.date.strftime("%Y-%m-%d") if !batch.date.nil? %></td>
<td id="two" style="display:" class="date-alert">
Microsoft Corporation
Microsoft Corporation
</td>
And then upon clicking it, you can execute like this:
$(".date-alert").click(function () {
// the current td is this
});

select2 breaks with ajax/jquery on pagination

I have a Rails 3.2.21 app which I use select2 for my dropdown menus and UI. In this view I'm doing a multi-select to pick different elements/objects in my view/form. When the initial controller view loads it's fine as you can see by the first picture. But when I click to a second page to paginate, the select2 is broken by the Ajax as you can see in the last picture.
Here is what my view looks like:
index.html.erb
<h3 class="offset3">5 most recent pages</h3>
<div class="row">
<div class="span3"><div class="well" id="form"><%= render 'form' %></div></div>
<div class="span9"><div id="pages"><%= render 'pages' %></div></div>
</div>
index.js.erb
$("#form").html("<%= escape_javascript render("form") %>");
$("#pages").html("<%= escape_javascript render("pages") %>");
_form.html.erb
<%= form_for(#page) do |f| %>
<div class="control-group">
<div class="controls">
<%= f.label :message %>
<%= f.text_area(:message, size: "40x2", :maxlength => 254, placeholder: "Enter your message here", required: true) %>
<%= f.label 'Unit'%>
<%= f.select :unit_id, options_for_select(Unit.active.order(:unit_name).map{ |unit| [unit.unit_name, unit.id] } + [["All Units", "all"]]), {:include_blank => true}, {:multiple => 'true', class: 'select'} %>
<%= f.label 'Region' %>
<%= f.collection_select(:region_id, Region.order("area ASC"), :id, :area, {:include_blank => true}, {:multiple => 'true', :class => 'select' } )%>
</div>
</br>
<%= f.button 'Send Page', class: 'btn btn-info', data: {disable_with: "<i class='icon-spinner'></i>Sending..."} %>
</div>
<% end %>
_results.html.erb
<table class="table table-striped">
<thead>
<tr>
<th>Incident Number</th>
<th>Patient Name</th>
<th>Transfer Date</th>
<th>Transferred From</th>
<th>Transferred To</th>
<th>Determinant</th>
<th>Unit</th>
<th>Insurance</th>
<th>Cancelation Reason</th>
<th>Billing Reference</th>
<th>Run Time</th>
<th></th>
</tr>
</thead>
<tbody>
<% #calls.each do |c| %>
<tr>
<td><%= c.incident_number %></td>
<td><%= c.patient_name %></td>
<td><%= c.transfer_date.strftime("%m/%d/%y") %></td>
<td><%= transferred_from(c) %><br/><%= transferred_from_address(c) %></td>
<td><%= transferred_to(c) %><br/><%= transferred_to_address(c) %></td>
<td><%= c.nature.try(:determinant)%></td>
<td><%= c.units.map(&:unit_name).join(", ") %></td>
<td><%= c.insurance.try(:insurance_type)%></td>
<td><%= c.cancel_reason.try(:reason) %></td>
<td><%= c.imx_num %></td>
<td><%= TimeFormatter.format_time(c.run_time) if c.in_service_time? %></td>
<td><%= link_to 'View', c, :class => 'btn btn-info btn-mini'%></td>
</tr>
<% end %>
</tbody>
</table>
<%= will_paginate #calls, :renderer => BootstrapPagination::Rails %>
Here is the jQuery from my application.js file:
$(function (){
$(".select").select2({
placeholder: "Select One",
allowClear: true
});
$(function() {
$("#pages th a, #pages .pagination a").live("click", function() {
$.getScript(this.href);
return false;
});
});
It looks like when I click a pagination link the dom is not getting reloaded and thus breaking the UI with select2. I can still pick objects in the form but UI-wise it's broken.
I was wondering if anyone could help point me in the right direction with this as I'm not very savvy with jQuery or javascript/ajax.
If my question is not clear or you need further examples, please let me know.
working
breaks on ajax pagination
So far this is the only useful answer I've come up with.
In my index.js.erb file I put the following:
$("select").select2({
placeholder: "Select One",
allowClear: true
}); init();
This will reinitialize select2 by destroying the call on an Ajax request then calling select2 again. It behaves as expected and keeps the UI properties while overriding the "turbolinks-like" Ajax behavior.
This is working 100% for me, although it feels a bit hackish that I have to do this in UJS, but hey whatever works right?

Iterate over an array by index when click on submit button Ruby on Rails

I have an array of Pet instances and each of them have a name, type, sex and size, etc... I'd like to iterate through this collection of Pet instances and display the each one by one.
This is what I have so far:
<% #pets.each do |pet| %>
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th>Sex</th>
<th>Age</th>
<th>breed</th>
<th>Size</th>
<th>Picture</th>
<th>Description</th>
<th>Shelter_id</th>
<th>Shelter</th>
<th>Phone</th>
<th>Email</th>
<th>City</th>
<th>Zip</th>
<th>Like</th>
</tr>
</thead>
<tbody>
<tr>
<td><%= pet.name %></td>
<td><%= pet.species %></td>
<td><%= pet.sex %></td>
<td><%= pet.age %></td>
<td><% pet.breeds.each do |breed| %>
<li><%= breed.name %></li>
<%end%>
</td>
<td><%= pet.size %></td>
<td><%= image_tag pet.picture %></td>
<td><%= pet.description %></td>
<td><%= pet.shelter_id %></td>
<% shelter = Shelter.find(pet.shelter_id)%>
<td><%= shelter.name %></td>
<td><%= shelter.phone %></td>
<td><%= shelter.email %></td>
<td><%= shelter.city %></td>
<td><%= shelter.zip %></td>
<td><%= form_for pet, :url => { :controller => "favorite_pets", :action => "create" }, :html => {:method => :post} do |f| %>
<%= f.text_field :id %>
<%= f.submit %>
<% end %>
</td>
</tr>
</tbody>
</table>
<%end%>
So now, I need two thinks.
1st
When a user clicks the submit button (<%= f.submit %>) to send a POST request i do not want the page to reload nor to redirected me to another page. I looked around and it seems like :remote => true included in the form_for would do the trick but i'd need more help with that.
2nd
I'd like to control the iterating through #pets so that only the first one is displayed pet[0] and every time I click on the <%= f.submit %> button not only does it not reload the page but it displays the next index in the array pet[1]
I think I need to set up a sort of counter which would increment the index of the pet array every time a user click on the <%= f.submit %> button.
Any guiding thoughts?
If I were to do this I would use some javascript. So your submit button turns into more of an "Add Button" it doesn't actually submit anything. It would just add that object (in your case the pet, along with its info) to a javascript array as well as display the new object (again the pet along with the info) on the window. Then create another button to actually submit all the pets. (The javascript array)

Rails jQuery sortable unable to save

I'm trying to make my table sortable (drag and drop) using jQuery, the problem I'm having is saving the new sorted table and then publishing it to other users or when the browser is refreshed.
I'm using:
gem 'acts_as_list'
Rails 3.2.17
ruby 1.9.3p484
Is there a better way of doing this?
my sort and show method on my controller
def sort
#episodes = current_user.episodes_for(#show).each do |episode|
episode.position = params['episode'].index(episode.id.to_s) + 1
episode.save
end
render :nothing =>true
end
def show
#episodes = current_user.episodes_for(#show)
#episodes.order('episode.position ASC')
#episode = #episodes.where(id: params[:id]).first
end
My Javascript
<script>
$(window).load(function() {
$("#sortthis").sortable({
axis: 'y',
placeholder: 'ui-state-highlight',
cursor: 'move',
dropOnempty: false,
scroll: true,
opacity: 0.4,
update: function(event, ui){
var itm_arr = $("#sortthis").sortable('toArray');
var pobj = {episodes: itm_arr};
$.post("/episodes/sort", pobj);
}
});
});
</script>
The table I wanna sort in views:
<tbody id='eps'>
<tr>
<th>Title</th>
<th>#</th>
<th>Season</th>
<th>Download?</th>
<th>Shared?</th>
<th>Length</th>
<th>Status</th>
<th></th>
</tr>
<% for episode in #episodes %>
<tr>
<td id="eps_<%= episode.id %>", width="20%"><%=h episode.title %></td>
<td id="eps_<%= episode.id %>"><%=h episode.number %></td>
<td id="eps_<%= episode.id %>"><%=h episode.season %></td>
<td id="eps_<%= episode.id %>"><%=h episode.is_downloadable %></td>
<td id="eps_<%= episode.id %>"><%=h episode.shared_with_dev %></td>
<td id="eps_<%= episode.id %>"><%=h episode.length %></td>
<td>
<% if episode.video %>
<%= link_to 'Replace Video', new_show_episode_video_path(episode.show, episode) %>
<% else %>
<%= link_to 'Upload Video', new_show_episode_video_path(episode.show, episode) %>
<% end %>
</td>
<td>
<%= link_to "View", [episode.show, episode] %>
<%= link_to "Edit", edit_show_episode_path(episode.show, episode) if permitted_to? :update, episode %>
<%= link_to "Delete", show_episode_path(episode.show, episode), :confirm => 'Are you sure?', :method => :delete if permitted_to? :delete, episode %>
</td>
</tr>
<% end %>
any help will be greatly appreciated!
I figured it out, made the following changes:
Views:
<tr id="<%= episode.id %>">
and new controller
def sort
Episode.all.each do |e|
if position = params[:episodes].index(e.id.to_s)
e.update_attribute(:position, position + 1) unless e.position == position + 1
end
end
render :nothing => true, :status => 200
end
finally added this to my model:
acts_as_list
default_scope order('position')
let me know if anyone's having similar issues.

Categories

Resources