Implement rails ajax search in rails 4.2.0 - javascript

I would like to implement ajax search to my rails application.So how do I proceed with my defined code.
I want to search with respect to the description, paid amount etc.
For better understanding follow the image;
index.html.erb
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div class="table-responsive myTable">
<table class="table listing text-center">
<tr class="tr-head">
<td>Date</td>
<td>Description</td>
<td>Amount</td>
<td>Discount</td>
<td>Paid</td>
<td>Balance</td>
</tr>
<tr>
<td></td>
</tr>
<a href="#" class="toggle-form" style="float: right;" >Search</a>
<div id="sample">
<%= form_tag xvaziris_path, remote: true, method: 'get', class: "form-group", role: "search" do %>
<p>
<center><%= text_field_tag :search, params[:search], placeholder: "Search for.....", class: "form-control-search" %>
<%= submit_tag "Search", name: nil, class: "btn btn-md btn-primary" %></center>
</p>
<% end %><br>
<% if #xvaziris.empty? %>
<center><p><em>No results found.</em></p></center>
<% end %>
</div>
<%= render partial: "xvaziri", collection: #xvaziris %>
</table>
</div>
</div>
</div>
_xvaziri.html.erb
<% balance = 0 %>
<tr class="tr-<%= cycle('odd', 'even') %>">
<td class="col-1"><%= xvaziri.date.strftime('%d/%m/%Y') %></td>
<td class="col-3"><%= span_with_possibly_red_color xvaziri.description %></td>
<td class="col-1"><%= number_with_precision(xvaziri.amount, :delimiter => ",", :precision => 2) %></td>
<td class="col-1 neg"><%= number_with_precision(xvaziri.discount, :delimiter => ",", :precision => 2) %></td>
<td class="col-1 neg"><%= number_with_precision(xvaziri.paid, :delimiter => ",", :precision => 2) %></td>
<% balance += xvaziri.amount.to_f - xvaziri.discount.to_f - xvaziri.paid.to_f %>
<% color = balance >= 0 ? "pos" : "neg" %>
<td class="col-1 <%= color %>"><%= number_with_precision(balance.abs, :delimiter => ",", :precision => 2) %></td>
</tr>
xvaziris_controller.rb
class XvazirisController < ApplicationController
before_action :set_xvaziri, only: [:show, :edit, :update, :destroy]
def index
#xvaziris = Xvaziri.where (["description LIKE ? OR amount LIKE ? OR paid LIKE ?", "%#{params[:search]}%","%#{params[:search]}%","%#{params[:search]}%"])
respond_to do |format|
format.js
format.html
end
end
def import
Xvaziri.import(params[:file])
redirect_to xvaziris_url, notice: "Xvaziris imported."
end
def show
end
def new
#xvaziri = Xvaziri.new
end
def create
#xvaziri = Xvaziri.new(xvaziri)
if
#xvaziri.save
flash[:notice] = 'Xvaziri Created'
redirect_to #xvaziri
else
render 'new'
end
end
def edit
end
def update
if #xvaziri.update(xvaziri)
flash[:notice] = 'Xvaziri Updated'
redirect_to #xvaziri
else
render 'edit'
end
end
def destroy
#xvaziri.destroy
flash[:notice] = 'Xvaziri was successfully destroyed.'
redirect_to xvaziris_url
end
private
# Use callbacks to share common setup or constraints between actions.
def set_xvaziri
#xvaziri = Xvaziri.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def xvaziri
params.require(:xvaziri).permit(:date, :description, :amount, :discount, :paid)
end
end
search.js
$(document).on('page:change', function () {
$("div#sample").hide();
$("a.toggle-formed").click(function(event) {
event.preventDefault();
$("div#sample").fadeToggle();
});
});
index.js.erb
$(#which_id?).append("<%= j render xvaziri %>");
How would I link the id in order to retrieve all the data from xvaziris#index page in js format ?
I added remote: true, respond to format.js etc
Any suggestions are most welcome.
Thank you in advance.

I revised my index.html and index.js.erb as below;
index.html.erb
<% #balance = 0 %>
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div class="table-responsive myTable">
<table id = "kola" class="table listing text-center">
<thead>
<tr class="tr-head">
<td>Date</td>
<td>Description</td>
<td>Amount</td>
<td>Discount</td>
<td>Paid</td>
<td>Balance</td>
</tr>
</thead>
<a href="#" class="toggle-formed" style="float: right;" ><strong>Search</strong></a>
<div id="sample">
<%= form_tag xvaziris_path, remote: true, method: :get, class: "form-group", role: "search" do %>
<p>
<center><%= text_field_tag :search, params[:search], placeholder: "Search for.....", autofocus: true, class: "form-control-search" %>
<%= submit_tag "Search", name: nil, class: "btn btn-md btn-primary" %></center>
</p>
<% end %><br>
</div>
<tbody>
<%= render #xvaziris %>
</tbody>
</table>
</div>
</div>
</div>
index.js.erb
<% #balance = 0 %>
$('#kola tbody').empty();
<% #xvaziris.each do |xvaziri| %>
$('#kola tbody').append("<%= j render xvaziri %>");
<% end %>

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.

gem 'gon' - name error in Quotes#index, uninitialized constant ActionView::CompiledTemplates::Gon, Rails 5

I am trying to use the gem 'gon' but run into the above error, stating;
namer error in Quotes#index
Showing /Users/jamesbkemp/Code/QuoteEngine/app/views/layouts/application.html.erb where line #5 raised:
uninitialized constant ActionView::CompiledTemplates::Gon
Any idea what the issue may be and or any suggestoins on alternative gems to make passing controller variables into javascript easier?
Thanks
application.html.erb, note line 5;
<!DOCTYPE html>
<html>
<head>
<title>QuoteEngine</title>
<%= Gon::Base.render_data %>
<%= csrf_meta_tags %>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
<%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
</head>
<body>
<%= render "layouts/navbar" %>
<% flash.each do |key, value| %>
<div class="alert alert-info alert-<%= key %>"><%= value %></div>
<% end %>
<%= yield %>
</body>
</html>
quotes_controller.rb
class QuotesController < ApplicationController
before_action :authenticate_user!, only: [ :new, :create, :edit, :update, :destroy ]
# before_action :owners_only, only: [ :show, :edit, :index, :update, :destroy ]
def new
#quote = Quote.new
end
def create
# #quote = Quote.new(quote_params)
#quote = current_user.quotes.new(quote_params)
if #quote.save
redirect_to quote_url(#quote), notice: 'Quote request created'
else
render :new
end
end
def show
# #quote = Quote.find(params[:id])
#quote = current_user.quotes.find(params[:id])
gon.gon_quote_id = #quote.id
end
def index
#quotes = current_user.quotes.all
end
def edit
#quote = current_user.quotes.find(params[:id])
end
def update
#quote = current_user.quotes.find(params[:id])
if #quote.update_attributes(quote_params)
redirect_to quote_path(#quote)
else
render :edit
end
end
def destroy
#quote = current_user.quotes.find(params[:id])
#quote.destroy
redirect_to quotes_path
end
private
def quote_params
params.require(:quote).permit(:gla, :prev_cover, :co_name, :co_number, :postcode, :industry, :lives_overseas,
:scheme_start_date, :payment_frequency, :commission_level)
end
end
_quote.rb partial;
<% #quote = local_assigns[:quote] %>
<section id="quotes">
<div class="container">
<div class="row">
<div class="col-md-4 text-center">
<div class="panel panel-success panel-quote link-panel">
<div class="panel-heading">
<strong>GLA</strong>
</div>
<div class="panel-body text-center">
<p><strong>Quote ID; <%= #quote.id %></strong></p>
</div>
<table class="table table-bordered">
<tr>
<td>Company name</td>
<td><%= #quote.co_name %></td>
</tr>
<tr>
<td>Company number</td>
<td><%= #quote.co_number %></td>
</tr>
<tr>
<td>Office postcode</td>
<td><%= #quote.postcode %></td>
</tr>
<tr>
<td>Industry</td>
<td><%= #quote.industry %></td>
</tr>
<tr>
<td>Previous cover</td>
<td><%= #quote.prev_cover %></td>
</tr>
<tr>
<td>Lives overseas</td>
<td><%= #quote.lives_overseas %></td>
</tr>
<tr>
<td>Scheme start date</td>
<td><%= #quote.scheme_start_date %></td>
</tr>
<tr>
<td>Payment frequency</td>
<td><%= #quote.payment_frequency %></td>
</tr>
<tr>
<td>Commission level</td>
<td><%= #quote.commission_level %></td>
</tr>
</table>
</div>
</div>
</div>
</div>
</section>
index.html.erb
<% #quotes.each do |quote| %>
<%= render :partial => "quote", locals: {quote: quote} %>
<% end %>
I would like to help with your case since I'm also using gon in rails 5 and it's working
after run bundle install,
open app/views/layouts/application.html.erb
and put under tag body <%= Gon::Base.render_data %>
do some test with open your your controller and create gon data (for example below I gave you with 10 users data
gon.users = User.limit(10)
open your coffee and test with log
alert gon.users
and don't forget to restart your rails server command

rendering form in partial with ajax, form does not function (ROR)

I'm fairly new to using ajax so I'm really hoping there is any easy fix to this. Currently what happens is I click 'New Schedule Entry' and a form gets appended to the table (see _form.html.erb). The issue is that the form does not work. Submit doesn't work, the date_picker/time_picker doesn't show up, the HTML5 validation doesn't pop up. I feel like there is a simple solution to this that I am missing.
Edit: To remove confusion, my current goal is to render the partial with ajax and have it submit normally, not remotely. If I render the form without ajax it works fine. Also if I add $('.datetimepicker').datetimepicker(); to new.js.erb, the date picker works correctly. I also removed turbolinks and I'm still having the same issue.
Relevant gems
gem 'turbolinks'
gem 'jquery-turbolinks' <--added because I was hoping this would fix the issue
gem 'jquery-rails'
new.js.erb
$('#schedule-table-tbody').prepend("<%= j(render partial: 'form') %>");
relevant part of index.html.erb
<%= link_to 'New Schedule Entry', new_schedule_path, remote: true %>
<div class="table-responsive">
<table id="schedule-table" class="table table-hover table-striped table-condensed">
<thead>
<tr>
<th class="col-xs-2">Date</th>
<th class="col-xs-2">Start Time</th>
<th class="col-xs-2">End Time</th>
<th class="col-xs-6">Details</th>
</tr>
</thead>
<tbody id="schedule-table-tbody">
schedules_controller.rb
class SchedulesController < ApplicationController
respond_to :html, :js
def index
#schedules = Schedule.page(params[:page]).per(20)
end
def show
#schedule = Schedule.find(params[:id])
end
def new
#schedule = Schedule.new
end
def create
#schedule = Schedule.new(schedule_params)
if (#schedule.save)
flash['main|success'] = 'Successfully created schedule entry.'
redirect_to schedules_path
else
render 'index'
end
end
private
def schedule_params
params.require(:schedule).permit(:name, :date, :start_time, :end_time)
end
end
_form.html.erb
<tr>
<%= simple_form_for #schedule do |f| %>
<td>
<%= f.input_field :date, :as => :date_picker, label: false %>
</td>
<td>
<%= f.input_field :start_time, :as => :time_picker, label: false %>
</td>
<td>
<%= f.input_field :end_time, :as => :time_picker, label: false %>
</td>
<td>
<%= f.input_field :name, label: false %>
</td>
<td>
<%= f.button :button, class: "btn btn-primary" do %>
<span class='glyphicon glyphicon-ok'></span> Save
<% end %>
</td>
<% end %>
</tr>
In the _form.html.erb you should put remote: true like this
<%= simple_form_for #schedule, remote: true do |f| %>
And you should place <tr> inside form like this. It works but i think it still ivalid markup. You should place <form> inside <td> or outside of <table>
<%= simple_form_for #schedule do |f| %>
<tr>
<td>
<%= f.input_field :date, :as => :date_picker, label: false %>
</td>
<td>
<%= f.input_field :start_time, :as => :time_picker, label: false %>
</td>
<td>
<%= f.input_field :end_time, :as => :time_picker, label: false %>
</td>
<td>
<%= f.input_field :name, label: false %>
</td>
<td>
<%= f.button :button, class: "btn btn-primary" do %>
<span class='glyphicon glyphicon-ok'></span> Save
<% end %>
</td>
</tr>
<% end %>
This is because you are using simple button not a submit button. Change f.button to f.submit
f.submit :button, class: "btn btn-primary" do %>
<span class='glyphicon glyphicon-ok'></span> Save
<% end %>

Ruby on Rails Display Amount of Characters Remaining for f.text_area

In my Ruby on Rails application I am trying to display the amount of characters remaining for the following text box in the view:
<%= f.label :review_text, 'Review Text:' %>
And am trying to do so through this java:
$(document).ready(function() {
$("#review_text").keyup(function() {
$("#counter").text(2000 - $(this).val().length);
});
});
Which displays the amount left through:
chars left : <span id="counter"><%= maxcounter=2000 %></span>
This does not work, but this text field does:
<%= text_field_tag :review_text %>
If I change the above to:
<%= f.text_field_tag :review_text %>
I get the following error:
NoMethodError in Reviews#new
undefined method `text_field_tag' for <ActionView::Helpers::FormBuilder:0x6b44020>
Can someone please help.
Below is the full view:
<%= stylesheet_link_tag "application", media: "all", "data-turbolinks-track" => true %>
<div id="contentWrapper">
<div id="content">
<div class='large_panel'>
<table>
<%= form_for #review do |f| %>
<%= f.hidden_field :user_id %>
<%= f.hidden_field :film_id %>
<%= image_tag "thor_hammer.jpg",:size => "900x250" %>
<h1>REVIEW <%= #review.film.title %>:</h1>
<tr>
<td width="500px">
<%= f.label :review_text, 'Review Text:' %></br>
</td>
</tr>
<tr>
<td>
<%= f.text_area :review_text, :size=>"50x10" %></br></br>
</td>
</tr>
<tr>
<td width="100px">
<%= f.label :no_of_stars, 'Stars:' %></br>
</td>
</tr>
<tr>
<td>
<%= f.select :no_of_stars, 1..5 %></br></br>
</td>
</tr>
<tr>
<td>
chars left : <span id="counter"><%= maxcounter=2000 %></span>
<%= text_field_tag :review_text %>
<div class="actions">
<%= f.submit 'Submit' %>
</div>
<div class="actions">
<%= link_to 'Back', reviews_path %>
</div>
</br></br>
<%= render "/error_messages", :message_header => "Cannot save: ", :target => #review %>
</td>
</tr>
<% end %>
</table><br>
</div>
</div>
</div>
<script>
$(document).ready(function() {
$("#review_text").keyup(function() {
$("#counter").text(2000 - $(this).val().length);
});
});
</script>
Tested and working:
reviews_controller.rb :
class ReviewsController < ApplicationController
def new
#review = Review.new
#maximum_length = Review.validators_on( :review_text ).first.options[:maximum]
end
end
review.rb :
class Review < ActiveRecord::Base
validates :review_text, length: { maximum: 200 }
end
new.html.erb :
<%= form_for #review do |f| %>
<%= f.text_field :review_text, maxlength: #maximum_length, id: 'review_text' %>
Chars left: <span id="counter" data-maximum-length="<%= #maximum_length %>"><%= #maximum_length %></span>
<% end %>
<script>
$(document).ready(function() {
var review_text = $("#review_text");
var counter = $("#counter");
var max_length = counter.data("maximum-length");
review_text.keyup(function() {
counter.text(max_length - $(this).val().length);
});
});
</script>
The accepted answers works as mentioned, however if your text_field is pre-populated with data, then when the page loads, the counter will not contain the correct count, to fix this add the following line just above review_text.keyup()
counter.text(max_length - review_text.val().length);
or just use the following updated script:
<script>
$(document).ready(function() {
var review_text = $("#review_text");
var counter = $("#counter");
var max_length = counter.data("maximum-length");
counter.text(max_length - review_text.val().length);
review_text.keyup(function() {
counter.text(max_length - $(this).val().length);
});
});
</script>

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