I am trying to implement a highchart that sums hours for a specified week. What it is currently doing is looking at my 'efforts' table and summing all records in that table. However I am trying to sum hours for a particular week, for the current user. I have the following snippet from my highcharts.html.erb.
series: [{
name: 'Hours',
data: [<% #efforts.each do |effort| %>
[Date.UTC(<%= effort.week_commencing.strftime("%Y,%m-1,%d") %>),<%= Effort.sum(:hours).
where(:week_commencing => week_commencing, :user_id => current_user.id)%>],<% end %>]
}]
});
});
I have the full code available on pastebin http://pastebin.com/ifbQfR0i
Is there a way around this?
Updated: Error message
NameError in Statistics#range
Showing /home/Project/app/views/statistics/range.html.erb where line
115 raised:
undefined local variable or method `week_commencing' for #<#:0x9fdadc8> Extracted source (around line #115):
name: 'Hours',
data: [<% #efforts.each do |effort| %>
[Date.UTC(<%= effort.week_commencing.strftime("%Y,%m-1,%d")
%>),<%= Effort.sum(:hours).
where(:week_commencing =>
week_commencing, :user_id => current_user.id)%>],<% end %>]
}] }); });
Efforts.rb
== Schema Information
Table name: efforts
id :integer(4) not null, primary key
project_task_id :integer(4)
user_id :integer(4)
week_commencing :date
hours :float
created_at :datetime
updated_at :datetime
I'm not quite sure, but shouldn't it be:
%>),<%= Effort.sum(:hours). where(:week_commencing => effort.week_commencing, :user_id => current_user.id)%>],<% end %>] }] }); });
instead of
%>),<%= Effort.sum(:hours). where(:week_commencing => week_commencing, :user_id => current_user.id)%>],<% end %>] }] }); });
Related
I have an employee dropdown that lists all the employees. I want to be able to select an employee and get the address of the employee from the model so that I may display it. the following is the code of my collection_select.
<div class="form-group col-md-2 field">
<%= form.label :employee_id %>
<%= form.collection_select :employee_id, Employee.all, :id, :full_name,{:prompt=>"Select Employee"},{:id=>"emp_select",class:"form-control",:onchange=>"getEmployee();"} %>
</div>
Next is the code I am using to grab the value of the employee that was selected and it does work.
function getEmployee() {
var selectedVal=$('#emp_select option:selected').val();}
From here what do I do to get the address of the employee that was selected?
You will have to retrieve the employee's address via ajax call. Here are the steps:
Define an action in your rails app to return employee's address by json.
Make an ajax request to that action and get the info needed.
Render result into view.
For more information, take a look at this link:
https://guides.rubyonrails.org/working_with_javascript_in_rails.html
routes.rb
controller :ajax do
get 'ajax/get_employee_address/:employee_id', action: :get_employee_address, as: :get_employee_address
end
ajax_controller.rb
class AjaxController < ActionController::Base
def get_employee_address
employee = Employee.find(params[:employee_id])
render json: employee.address.to_json
rescue ActiveRecord::RecordNotFound
render json: 'Employee not found', status: 422
end
end
Your js code
function getEmployee() {
var selectedVal=$('#emp_select option:selected').val();
$.ajax({
url: '/ajax/get_employee_address/' + selectedVal,
success: function (address) {
// Render your address to view
},
error: function () {
// Handle error here or just return nothing
return null;
}
})
}
Note: This ajax endpoint will expose your employee address to outside so be sure to make authentication to prevent leaking info.
Add address to option data-attribute:
<%= form.select :employee_id,
options_for_select(Employee.all.map {
|e| [e. full_name, e.id, { 'data-address' => e.address }]
}),
{ prompt: "Select Employee" },
{ id: "emp_select", class: "form-control", onchange: "getEmployee();" } %>
On change get it with js:
function getEmployee() {
var selectedVal=$('#emp_select option:selected').data("address");}
And insert it to needed place
I have a page that does a search, using javascript, and I want to take the list of users that it comes up with, and send that as a submit to the next page. What I have, is:
.search_client_users
= form_tag admin_clients_path, method: "get" , class: "search_form" do
= label_tag 'search_term', 'Old domain name:'
= text_field_tag 'search_term', nil, autocomplete: "off", size: "50"
.main_form.client_emails
= simple_form_for(:domainNameSwap, url: { action: "update" }, html: { method: :put }) do |f|
.input-row
= f.hidden_field :users, value: #clients
.submit-row
.row
.col-xs-5
.submit
= f.submit "Update domains", id: "submit", :class => "btn btn-primary submit"
.client_list
- content_for :javascript do
= javascript_include_tag 'admin/search_client_users'
[some of the formatting may not be quite right due to cut and paste, sorry]
The admin/search_client_users creates an #clients, I'm pretty sure, at least, with:
class App.ClientUserList
constructor: ->
#incrementalSearchAttempts = 0
search: (searchTerm, completeCallback) =>
handleResponseWithOrderAwareness = (attemptNumber, response) =>
if attemptNumber >= #incrementalSearchAttempts
completeCallback(response)
#incrementalSearchAttempts++
onComplete = _.partial(handleResponseWithOrderAwareness, #incrementalSearchAttempts)
$.get('/admin/manage_clients/client_list', { search_term: searchTerm }).complete(onComplete)
class App.Views.SearchClientUsers extends Backbone.View
events:
"keyup input[name='search_term']": "search",
"click .profile_attribute": "showClientUserProfile"
initialize: =>
#clientUserList = new App.ClientUserList()
search: =>
searchTerm = $('.search_form input[name=search_term]').val()
#clientUserList.search(searchTerm, #render)
showClientUserProfile: (event) =>
window.location = $(event.currentTarget).closest('tr').data('client-path')
render: (response) =>
#$el.find('.client_list').html(response.responseText)
$ ->
new App.Views.SearchClientUsers(el: $('.search_client_users')).search()
so, I'm trying to take the list of clients, and send it to the update method in the controller. However, due to when javascript and ruby take place, it doesn't seem to be working... is there a way to do this? or do I have to figure out how to do this in Ajax?
ETA: An alternative idea is, I suppose to just turn the initial text_field into a form, so that the text field is used both for the javascript, and THEN submitted to the form, and then the update can re-do the search... My dataset is small enough that doing the search twice is not a huge problem I suppose...
But I'm not quite sure exactly how to merge the two forms...
I'm using Highcharts to make graphical representation of my data in my tables. I can get the data to be show on the charts but to do so I find myself having to code each record one by one like this:
Model:
def self.subject_analysis(subject_type)
Note.where(:subject_type => English).count if subject_type == :English
Note.where(:subject_type => Geography_Class_C).count if subject_type == :Geography_Class_C
Note.where(:subject_type => Maths_Class_B).count if subject_type == :Maths_Class_B
Highcharts js
...
},
series: [{
name: 'Number of notes By Class Module',
data: [<%= Note.where(:subject_type => 'English').count %>, <%= Note.where(:subject_type => 'Geography Class C').count %>, <%= Note.where(:subject_type => 'Maths Class B').count %>]
}]
});
This works but obviously this is far from ideal and not what I need. I would just like the charts to update from the table automatically when the table changes because a new record has been added.
Would appreciate any guidance. Thanks.
you can make use data attributes
define #my_var in controller
#my_var = Note.where(:subject_type => English).count
on view <div id='english' data-note='<%= #my_var %>'>
than in your js file
eng = $('#english').data('note')
and pass it to highcharts code
I ve used the fullcalendar assets gem for listing out all the events in the calendar, i have tried to modify the calendar as per my needs but for this scenario i am getting confused.
Ive used https://github.com/bokmann/rails3_fullcalendar
Scenario:
I have to filtered out all the appointments in the calendar for a particular worker. so in my appointments controller ive listed all the appointments in this way.
#appointments = #client.appointments
and it is listing all the appointments of a client, so now i ve to again filter out the appointments based on the selection of drop down button where i am listing all the workers of the client. so based on the worker selected, it will show the appointments of that particular selected worker.
Code tried
1. Rails Way
First i ve tried in the rails way that i needed to pass the id of the worker from the drop down to the controller, the code for drop down i ve used:
<%= form_tag appointments_path do %>
<%= select_tag(:worker_id, options_from_collection_for_select(#client.workers, :id, :alias), :include_blank =>true)%>
<%=submit_tag "Display"%>
<% end %>
But i dont know what to pass in the controller for fetching the records.
2. JS way
<%= select_tag(:worker_id, options_from_collection_for_select(#client.workers, :id, :alias), :include_blank =>true),:onchange => 'a(this.value)'%>
calendar.js
function a(pointer){
var intWorkerId = pointer;
alert(intWorkerId);
$.ajax({
url:'/appointments',
dataType: "json",
data:({
id:intWorkerId
}),
type:'get',
success:function(result){
alert(result);
$('#content').html(result);
console.log(1);
}
});
}
Some how the id of a worker i am getting in the controller as i ve tried to print the value and tried also to print the values from that id and it is correct but i dont know how to proceed.
Appointment.rb
def as_json(options = {})
{
:id => self.id,
:title => self.title,
:description => self.description || "",
:start => appointment_start_time.rfc822,
:end => appointment_end_time.rfc822,
:allDay => self.all_day,
:recurring => false,
:url => Rails.application.routes.url_helpers.appointment_path(id)
#:color => "red"
}
Appointment_controller.rb
if params[:id]
##appointments = #client.workers.params[:id].appointments
#p "*********id values****#{params[:id]}"
#worker = Worker.find(params[:id])
#p"***** #{worker.alias}"
##appointments = worker.appointments
#p "******* #{#appointments.count}"
p "*******hello id is here*******"
else
#appointments = "hello"
p "*******hello id is not here*******"
end
I ve tried every possible combination but not able to get results. Please help me.
Thanks
If appointments is an association on Worker you can get the clients worker like this:
#worker = #client.workers.find(params[:id])
The get that worker's appointments:
#appointments = #worker.appointments
This is assuming that in your Appointment class you have:
class Appointment < ActiveRecord::Base
belongs_to :worker
end
And your Worker:
class Worker < ActiveRecord::Base
has_many :appointments
end
In your controller you also need to get the #client. How are you currently doing that? Is it current_user? If not you need to pass in the client id in your form:
<%= form_tag appointments_path do %>
<%= select_tag(:worker_id, options_from_collection_for_select(#client.workers, :id, :alias), :include_blank =>true)%>
<%= hidden_field_tag :client_id, session[:client_id] # or wherever you store this
<%=submit_tag "Display"%>
<% end %>
Now you can find the client in your controller:
#client = Client.find(params[:client_id])
Also note that in the example form you provided you're passing the id of the worker as :worker_id, so you need to use params[:worker_id] in your controller. The JS example you provided uses :id so I'm assuming that's the approach you're going with since you use params[:id] in your controller example.
Finally, return the appointments as a JSON array:
class AppointmentsController < ApplicationController
def index
if params[:id]
#appointments = #client.workers.find(params[:id])
render json: #appointments.map(&:as_json)
else
#appointments = "hello"
p "*******hello id is not here*******"
end
I found the solution by re-rendering the calendar once again in the same js file
function RenderCalendar(eId) {
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
defaultView: 'agendaWeek',
aspectRatio: 1.5,
slotMinutes: 30,
slotEventOverlap: true,
editable: true,
timeFormat: 'h:mm t{ - h:mm t} ',
titleFormat: {
month: 'MMMM yyyy', // September 2009
week: "| MMM d[ yyyy] { '—' MMM d | yyyy}", // |Sep 7 - Sep 13|, 2009
day: 'dddd, MMM d, yyyy' // Tuesday, Sep 8, 2009
},
events: {
url: '/appointments',
cache: true,
type: 'GET',
data: {
id: eId
},
error: function () {
alert('there was an error while fetching events!');
},
},
Prior to Rails 3, I used this code to observe a field dynamically and pass the data in that field to a controller:
<%= observe_field :transaction_borrower_netid,
:url => { :controller => :live_validations, :action => :validate_borrower_netid },
:frequency => 0.5,
:update => :borrower_netid_message,
:with => "borrower_netid" %>
I'm trying to update that code to work with Jquery and Rails 3, but I can't get it to work. I updated my routes.rb to include
match "/live_validations/validate_borrower_netid" => "live_validations#validate_borrower_netid", :as => "validate_borrower"
and I'm trying to observe the field and make the necessary calls with:
jQuery(function($) {
// when the #transaction_borrower_netid field changes
$("#transaction_borrower_netid").change(function() {
// make a POST call and update the borrower_netid_message with borrower_netid
$.post(<%= validate_borrower_path %>, this.value, function(html) {
$("#borrower_netid_message").html(html);
});
});
})
but it's not working. My Javascript and Jquery skills are severely lacking, so any help anyone could provide would be much appreciated. Thanks!
You need to wrap your <%= validate_borrower_path %> in quotes:
$.post("<%= validate_borrower_path %>", this.value, function(html) {
I ended up using the following:
$('#transaction_borrower_netid').live('change', function() {
// when the #transaction_borrower_netid field changes
// make a POST call and replace the content
var netID = $('#transaction_borrower_netid').val();
$.post("/live_validations/validate_borrower_netid", { borrower_netid: $('#transaction_borrower_netid').val() }, function(html) {
$("#borrower_netid_message").html(html);
});
})