I have a calculated number that I wish to use to send as a value in a
hidden_field in a form. This started out as a question, but I figured
it out so I’ll post it anyway as a FYI for Ruby N.s like me or if
anyone can think of a smarter way.
A few points:
*The value is calculated in the controller and assigned to an instance
variable
*The ‘TimeOff’ model is in a has_many relationship with the ‘Employee’
model (An Employee can take many days off).
*The resulting value is being passed as a hidden_field to populate the
table ‘time_offs’
Either of these work:
<%= hidden_field "time_off", "hours_left", :value =>
“#{pto_accrued}” %> <%= hidden_field “time_off”,
“hours_left”, :value => @pto_accrued %>
Below is my code:
Employee Model
####################################
class Employee < ActiveRecord::Base
has_many :time_offs
end
TimeOff Model
####################################
class TimeOff < ActiveRecord::Base
belongs_to :employee
end
Employee Controller
####################################
class EmployeesController < ApplicationController
…
def timesheets_and_time_off
# Employee parameters being passed
@employee = Employee.find(params[:id])
# The block below calculates Time Off for an employee
start_date = (@employee.hire_date).to_time
end_date = Time.now
days = ((end_date - start_date)/(3600*24))
accumulated_pto = ((days/14)*1.54)
# Final Value for my View
@pto_accrued = accumulated_pto
end
This is the ‘create’ method for Time Offs that belong to an Employee
def create_pto
Employee.find(params[:id]).time_offs.create(params[:time_off])
flash[:notice] = “PTO Was Successfully Added”
redirect_to :action => “timesheets_and_time_off”, :id => params[:id]
end
…
end
View (timesheets_and_time_off.rhtml)
If there are no Time Offs for the employee, it will only show a
‘Calculate’ button, which calculates from the Employee.hire_date.
Once it is calculated the total will appear in a table.
######################################
…
Paid Time Off
<% if @employee.time_offs.blank? %>No time off has been recorded yet. Click 'Calculate' to generate a total.
<% form_tag :controller => ‘employees’, :action => ‘create_pto’, :id
=> @employee do %>
<%= hidden_field “time_off”, “hours_left”, #{pto_accrued} %>
<%= image_submit_tag(“calculate”) %>
<% end %>
<% else %>
Date | Hours Before | Hours Taken | Hours Left |
---|
Add PTO
<% form_tag :controller => 'employees', :action => 'pto', :id => @employee do %>Hours Taken (<%= @pto_accrued %> hrs available)
<%= text_field "time_off", "hours_taken" %>
<%= image_submit_tag(“save”) %>
<% end %>
<% end %>