Date and Date Ranges in Rails 3 - ruby-on-rails-3

I have a Rails 3 application with a prescription model. The model has a number of fields, two of them are to calculate and display the duration of a prescription.
At the moment the user enters a value in a text field such as '3 Months' and then manually changes a datetime input to three months from now. This seems like a perfect form to automate for the user.
Currently the fields are like this:
Duration of Treatment
<%= f.text_field :duration, :class => "input-text" %>
Date of Expiry
<%= f.datetime_select :expiry, :order => [:day, :month, :year], :class => "input-text" %>
So, my question. How can I create two dropdown lists for the duration field such as:
[1] [Day]
The user can select the number from the first list and in the second they can choose Day, Week or Month.
The value they pick using the duration select boxes would be saved as a text string e.g. "1 month" and the value of the Time.now in 1 month would be saved as a datetime value in the expiry column.
Is something like this possible to do? If so, how?

I'll provide an example of how you'd use the chronic gem, since it seems tailor-made for this purpose:
require 'chronic'
duration = "3 months" # => "3 months"
Time.now # => 2012-07-09 18:43:50 -0700
Chronic.parse(duration + " from now") # => 2012-10-09 18:43:55 -0700
If I understand your use case correctly, you can then just get rid of the datetime select entirely. Ask the user for the text duration and assign that to the text attribute. Then use chronic to determine the time value from the text parameter and assign that to the datetime attribute. For extra credit get the parsed time value asynchronously and display it on the page before they submit the form so they can see that what they are submitting makes sense.

You can just do something easy like:
Time.now + 10.days
Source: How to add 10 days to current time in Rails
And how to do drop-downs?
Drop down box in Rails
Assuming the prescription is valid at the time of object creation, you can store the start date in the database as the current time Time.now (may want to convert to a datetime) and then based on the drop-down, add the amount of time until it expires like off the top of my head:
eval "Time.now + #{params[:prescription][:amount].#{params[:prescription][:time_type]}"
Hope that made sense. I would look up a better way to add the time though that maybe doesn't use eval. Heres the time reference: http://api.rubyonrails.org/classes/Time.html

First, change your duration field to a select menu with 1-30, or whatever numbers you want.
Then in the controller action that handles your form:
#prescription = Prescription.new(params[:prescrption])
#prescription.duration = "#{pluralize(params[:prescription][:duration], params[:prescription][:expiry])}"
if params[:prescription][:expiry] == "Day"
#prescription.expiry = Time.now + params[:prescription][:duration].days
elsif params[:prescription][:expiry] == "Week"
# Put week logic here
elsif params[:prescription][:expiry] == "Month"
# Put month logic here
end
# Put the rest of the #prescription.save stuff here.
It's a little verbose, but I think that's kind of the way it is with the way time is set up in Ruby...

Related

Ruby on Rails: Creating a Calendar, get the next week (redirect loop)

I'm creating a Calendar to view of a week without the Calendar gem. (It will get pretty specific past the use of that gem).
When I render a view to see a page (index) it will display the dates and days for that particular week. How can I make a button that is clickable that will change those dates to the previous week or the next week?
I'm confused on how to do it, and am looking for coding suggestions of course. How I have attempted this so far is I have created two helper functions to add the days to my current variables. Then I want to display the same page after the helper function updates to the next week or previous week.
Here is how I am calling my helper function
<%= link_to '<', week_ahead, class: 'month-arrow' %>
def week_ahead
#viewDate = #viewDate + 7.days
#weekStart = #viewDate.beginning_of_week(start_day = :monday)
end
helper_method :week_ahead
def week_back
#viewDate = #viewDate - 7.days
#weekStart = #viewDate.beginning_of_week(start_day = :monday)
end
helper_method :week_back
Here is what I am using in my controller
def index
#user = User.find(session[:user_id])
#viewDate = Date.today
#weekStart = #viewDate.beginning_of_week(start_day = :monday)
end
If I put a redirect_to user_path command in the helper function it gives a redirect loop. I still want my view to update to the next week when they click on the "next arrow".
Use simple calender gem. It is really helperful.https://github.com/excid3/simple_calendar

simple_form date not working after the 12th of each month

Has anyone run into this problem? I have a User object and a simple_form which asks for the User's birthday.
<%= f.input :birthday, as: :date, start_year: Date.today.year - 70,
end_year: Date.today.year, order: [:month, :day, :year], label: false %>
Any date I pick I can only pick a day up to the 12th of each month. If I pick 13th or higher simple_form says "Please enter a valid date". Very strange.
I got this code from https://github.com/plataformatec/simple_form and all it says about this code is "SimpleForm accepts same options as their corresponding input type helper in Rails". Does anyone know where the corresponding input type helper in Rails is documented?
I would guess that you've confused :day and :month somewhere.
Or maybe, put differently, you want to use the American format and instead you're using the european format (or the reverse). Not sure it will help, but see this link:
How can I use US-style dates in Rails using Ruby 1.9?

Datepicker ui with formtastic, rails 3.1

I use rails 3.1, formtastic 2.0.2 and datepicker ui
I made datepicker_input.rb:
class DatepickerInput < Formtastic::Inputs::StringInput
include Formtastic::Inputs::Base
def input_html_options
super.merge(:class => "datepicker")
end
end
In application.js I wrote:
$('input.datepicker').datepicker()
I use it in my form like :as => :datepicker. I see calendar, pick date and everything is fine except for it doesn't fill column in my model. The only thing that I noticed is that when I fill first date and then all the other fields - it works. When date field is the last - it doesn't work. There is no errors, params[:model_name][:date_field] is not empty just nil in place of date that I chose.
Error was in date format - database just couldn't take format that returned datepicker.

Searching ActiveRecord by DateTime not working

I asked a question regarding this yesterday, but it was muddled and didn't make sense, so I'm going to boil it down to the core issue.
I have an entries table. When a new record is saved, the entries_controller adds a time to the date column, which is recorded as a datetime. In the new method, I declare a new DateTime as so:
#entry.date = DateTime.new( params[:year].to_i, params[:month].to_i, params[:day].to_i )
I then include it as a hidden field with formtastic:
<%= f.input :date, :as => :hidden %>
Once the entry is saved to the database, the date field looks like 2011-02-10 00:00:00. Everything is working as planned so far, but when I try to retrieve that entry by querying against the date field, I get nil.
I've tried:
search_date = DateTime.new(2011,2,10)
Entry.find_by_date(search_date)
=> nil
I've even tried to search by string, which doesn't make sense since it's a datetime field.
search_time = '2010-02-10 00:00:00'
Entry.find_by_date(search_date)
=> nil
What am I doing wrong here? Why can't I retrieve the record by date?
Would this work for you?
Entry.where("date = #{search_date}")
I just tested this in Rails 3.0.4, mysql2 0.2.6 and
Entry.find_by_date(DateTime.new(2011,2,10))
works.
Having said that, why are you using a datetime column to save a date? Other than it just being a bad idea, you possibly could be running into some kind of timezone issues based on your rails and sql settings. Some automatic timezone conversion could explain the behaviour you are observing but that's just a guess. Please check the development server logs to see if rails is indeed generating the query you wish it to generate.

Rails 3 Need help with next month on a calendar

is it possible to advance a variable something like #current_month = Date.today.month+1 then forward it back to the index page, if so how
#current_month = Date.today + 1.month
Not sure quite what you mean by 'forward it back to the index page', but if you then
render :action => 'index'
the #current_month instance variable will be available to the index view of that controller. You could print out the month only by using strftime, eg <%= #current_month.strftime("%B") %>
Check out .strftime at http://www.ruby-doc.org/core/classes/Time.html#M000392
For calendar operations, one probably wants to start at the beginning of the month.
#current_month = 1.month.from_now.beginning_of_month
This will return a ActiveSupport::TimeWithZone object which is similar to Ruby's DateTime.
OR
#current_month = Date.today.at_beginning_of_month.next_month
which will return a Ruby Date object.