Separate date and time form fields in Rails - datetime

I have an ActiveRecord model Eventwith a datetime column starts_at. I would like to present a form, where date and time for starts_at are chosen separately (e.g. "23-10-2010" for date and "18:00" for time). These fields should be backed by the single column starts_at, and validations should preferably be against starts_at, too.
I can of course muck around with virtual attributes and hooks, but I would like a more elegant solution. I have experimented with both composed_of (rdoc), and attribute-decorator (lighthouse discussion, github) without success.
Below is a rough outline of what I would like..
class Event < ActiveRecord::Base
validates_presence_of :start_date
end
# View
# On submission this should set start_date.
form_for #event do |f|
f.text_field :starts_at_date # date-part of start_date
f.text_field :starts_at_time_of_day # time-of-day-part of start_date
f.submit
end
Any help appreciated.

Do you have to have a text_field in the view?
As far as I can tell, you can have a date_time field and then just use two different input fields to set the different parts of the field.
form_for #event do |f|
f.date_select :starts_at
f.time_select :starts_at, :ignore_date => true
f.submit
end
Since the rails date and time select helpers set five different parameters (starts_at(1i) for the year part, 2i for the month part, and so on), that means that the date_select only sets them for the date part, while if you pass :ignore_date => true to the time_select, it will only set the hour and minute part.
If you must have a text_field I'm not sure how to do it, but it might be possible to do using some jQuery magic before setting the datetime parameters before sending the form.

Was looking at this today for a Rails project, and came across this gem:
https://github.com/shekibobo/time_splitter
Setting DateTimes can be a difficult or ugly thing, especially through a web form. Finding a good DatePicker or TimePicker is easy, but getting them to work on both can be difficult. TimeSplitter automatically generates accessors for date, time, hour, and min on your datetime or time attributes, making it trivial to use different form inputs to set different parts of a datetime field.
Looks like it would do the job for you

Using a date_select and time_select is a good way to go.
However, I wanted a text_field for the date (so I can use a JavaScript date picker).
Using strong_parameters or Rails 4+:
models/event.rb
# Add a virtual attribute
attr_accessor :start_at_date
views/events/_form.html.haml
- # A text field for the date, and time_select for time
= f.label :start_at
= f.text_field :start_at_date, value: (f.object.start_at.present? ? f.object.start_at.to_date : nil)
= f.time_select :start_at, :ignore_date => true
controllers/events_controller.rb
# If using a date_select, time_select, datetime_select
# Rails expects multiparameter attributes
# Convert the date to the muiltiparameter parts
def event_params
if !!params[:event] && (params[:event]["start_at(4i)"].present? || params[:event]["start_at(5i)"].present?)
if params[:event][:start_at_date].present?
start_at_date = params[:event][:start_at_date]
else
start_at_date = Date.today
end
year = start_at_date.match(/^(\d{4})[\-\/]/)[1]
month = start_at_date.match(/[\-\/](\d{2})[\-\/]/)[1]
day = start_at_date.match(/[\-\/](\d{2})$/)[1]
params[:event]["start_at(1i)"] = year
params[:event]["start_at(2i)"] = month
params[:event]["start_at(3i)"] = day
end
...

Elegant solution may provide date_time_attribute gem:
class MyModel < ActiveRecord::Base
include DateTimeAttribute
date_time_attribute :starts_at
end
It will allow you to set starts_at_date and starts_at_time separately:
form_for #event do |f|
f.text_field :starts_at_date
f.text_field :starts_at_time
f.submit
end
# this will work too:
form_for #event do |f|
f.date_select :starts_at_date
f.time_select :starts_at_time, :ignore_date => true
f.text_field :starts_at_time_zone
f.submit
end
# or
form_for #event do |f|
f.date_select :starts_at_date
f.text_field :starts_at_time
f.submit
end
It will also allow you to play with time zones, use Chronic etc.

Is this because of a design issue? It is really much easier if you just save starts_at as a datetime data type and use something like:
http://puna.net.nz/timepicker.htm#
It simply runs on top of whatever date fields you have for your model.

Related

Rails conditional CSS in view helper

I have a simple rails app and I'm trying to write a view helper that does the following.
Compares two values. If the current_month amount is greater than the forecast amount then make the text green. If the current_month amount is less than the forecast amount then make the text red.
I wrote out this simple helper to append text to the output of the the rails method, but I'm unsure of how to inject CSS/styling into this.
def target_hit(forecast, current)
(if current.amount > forecast.amount
number_to_currency(current.amount.to_s) + " Yay"
elsif current.amount < forecast.amount
number_to_currency(current.amount.to_s) + " No dice"
end).html_safe
end
I'm pretty proficient on the backend but when it comes to front-end stuff I'm stumbling a lot. Any help would be greatly appreciated.
example view code
<p class='total'>Current: <%= target_hit(#forecast, #current) %></p>
The rails helper content_tag http://apidock.com/rails/ActionView/Helpers/TagHelper/content_tag, is useful and means you don't have to use html_safe. I try to move all the logic from the views to helpers to make the view easy to read e.g.
def target_hit(current_amt, forecast_amt)
content_tag(:p, "#{number_to_currency(current_amt.to_s)} target_content(current_amt, forecast_amt)", class: "total #{target_class(current_amt, forecast_amt)}")
end
def target_content(current_amt, forecast_amt)
forecast_reached?(current_amt, forecast_amt) ? "Yay" : "No dice"
end
def target_class(current_amt, forecast_amt)
forecast_reached?(current_amt, forecast_amt) ? "green" : "red"
end
def forecast_reached?(current_amt, forecast_amt)
current_amt >= forecast_amt
end
in the view, you just call the helper method
<%= target_hit(#current.amount, #forecast.amount) %>

ASP, Forms and passing variables between frames

I am pretty new to ASP, I know VBScript reasonably well though. What I am trying to do is create a website with 2 frames. In the top frame, it asks for a year (from a selection box) and a week number (from a selection box). It should then display the dates relating to the selection and a button to process the request. When the button is clicked the bottom form then processes a SQL query based on the selection in the top frame and displays the info.
Now, my problem is when it comes to understanding ASP. With ASP, all the code is processed then the output is sent to the browser. How do you update variables or even pass them to other frames when the code has already processed?
I just need some pointers on the way forward to accomplishing the above.
Thanks
First off, don't use frames: they're annoying, ugly, and outmoded.
You can do something like this in asp, but it's going to require a round trip (or two) to the server.
The basic outline of the page (let's call it thispage.asp) would be something like
<html><head>[head stuff]
<%
dim yr, wk, i
yr = request.form("Year")
wk = request.form("Week")
'- if you use form method='get', then use request.querystring("Year")
if not isnumeric(yr) then
yr = Year(date) 'or whatever else you want to use as a default
else
yr = CInt(yr)
end if
'similar validation for wk
%>
</head>
<body>
<form method="post" action="thispage.asp">
<select name="Year" size="1">
<%
for i = Year(Date) - 2 to Year(Date) + 2
response.write "<option value='" & i & "'"
if i = yr then response.write " selected"
response.write ">" & i & "</option>"
next
%>
</select> [similar code for week or date or whatever]
<input type="submit">
</form>
<%
If yr <> "" and wk <> "" Then
'- look up stuff in database and output the desired data
'- (this part will be much longer than this)
Else
Response.Write "<p>Please make your selections above.</p>"
End If
%>
</body></html>
If you need to output form fields that are dependent on the user's initial year & week selections, then you're going to need more than one trip to the server, but it's still the same idea: set up the variables you're going to need, see if they have values, write out the form, and then if all the necessary variables have all the necessary values, then you can do your output stuff.

Displaying attributes of associated models in a datagrid column

I have two models: User and Dog. I want to be able to show them both in a single Datagrid report. What syntax do I use to refer to a specific attribute of the user model when using the column() method? Right now I am just displaying the User object but I would like to display various columns with :name, :gender and :age attributes of the User model.
class User < ActiveRecord::Base
attr_accessible :email, :age, :gender, :name
has_many :dogs
class Dog < ActiveRecord::Base
attr_accessible :name, :age
belongs_to :user
class DogReport
include Datagrid
#
# Scope
#
scope do
Dog.includes(:user)
end
#
# Filters
#
filter(:dog_id, :integer)
#
# Columns
#
column(:id)
column(:name)
column(:age)
column(:user)
end
column(:user, :header => "user.name") do
self.user.name
end

How do I get a time stamp with ASP Classic from code?

I am using:
<%= time %>
It's returning:
5:12:19
And it's 8:12:19 p.m. where I am
How can I make it print the local time?
You have to set the LocaleId (Session.LCID or SetLocale(lcid)) for your own timezone before calling time. See more about SetLocale and LocaleIDs on this page
<% myDateTime = DateAdd("h", 3, Time) %>

asp date query formatting

i want to make an asp query so that an event is shown when it's date is greater or equal.
here's the code so far, but it doesn't work.
<%
strDateNow = date
strDateEvent = "30.05.2011"
%>
<% if strDateEvent >= strDateNow then %>
HELLO
<% end if %>
thanks for any help,
alex
I assume this is VBScript + Classic ASP rather than .net?
strDateEvent is a string so the >= is not comparing dates.
To compare against strDateNow which is a date despite its name, you need to convert strDateEvent to a date in order to compare:
If CDate(strDateEvent) >= strDateNow Then
If this fails with a type error then the format "30.05.2011" cannot be converted so use another; "10/04/2011" (ensuring dmy order is appropriate for your locale)

Resources