Rails convert datetime to date - ruby-on-rails

I just need 1 instance where I have a date field instead of a datetime field. No need in creating a new column just for 1 date.
How do I convert datetime to date when displaying data?
HTML that needs converting;
<td> <%= product.pDate %> </td>

There are actually a number of approaches you can take in Rails. Link Nguyen's answer is the pure Ruby approach, which works here and would also work in other Ruby contexts outside of Rails.
Rails also adds #to_formatted_s and #to_s (they're aliases of one another) to the date and time objects, e.g.:
<%= product.pDate.to_s(:long) %>
Rails define some date formats by default, and you can add your own by adding values to the Date::DATE_FORMATS array in an initializer (see the docs for examples).
A additional, slightly newer approach uses the locale files (e.g., config/locales/en.yml) to define formats, which can then be accessed in your views using the l (for localize) helper:
# Your ERb file
<%= l product.pDate, format: :short %>
# Your configs/locale/xx.yml file
# NB: `short` is defined by default but you can redefine it if you want
en:
date:
formats:
short: "%m/%d/%y"
See the Rails i18n guide for more.
The advantage of both Rails approaches is that you can decide on a standard style, or collection of standard styles, that you apply to dates/times everywhere in your app. If you were to decide to switch from two-digit years to four, or vice versa, the strftime approach would require editing every view (and not missing any), but with either Date#to_s or l() you change the configuration format in one place. The i18n approach allows you to further customise date formats for international markets if you want to (for example, day/month/year is an almost exclusively US ordering, so you might want to use a different format for other languages).

You can try strftime. for example product.strftime("%m/%d/%Y")

Related

ActiveScaffold search date range

I am developing a Rails application using ActiveScaffold.
The thing is that I need to filter a list of results by a date range.
(SQL equivalent 'BETWEEN ? AND ?')
I know that ActiveScaffold has a feature that already does that, but it has too many options.
(Past, Future, Range, =, ...., Between). In this case, I only need the Between option in that combo.
I tried overriding the field using the Helper, but the closest I got was to display 3 different combos (one for year, one for month, one for day).
Is there any way to override Active Scaffold so that only displays the "Between" option?
EDIT
Active Scaffold already does the search part well.
I am trying to change the visual part so it doesn't display so many options.
EDIT 2
The calendar plugins for rails are dated from 2009 or they aren't under maintenance.
You can use a range as a parameter in AR.
Model.where(:date => from..to)
Also, I'm not sure if ActiveScaffold has something to do with it. Normally, all the tasks like this one can be perfectly solved within plain ActiveRecord.
EDIT:
As it turns out, author also needs to get the user's input for the boundaries.
This is a common task that can be solved with one of the thouhands js plugins for datepickers.
I would recommend you not to stick to ActiveScaffold for that purpose.
Try this simple Jquery datepicker, and it will turn normal text field into that drop-down calendar. You will only need several lines of javascript then.
If you need further advise, just ask.

Rails wont return decimals correctly

I'm using Rails 3.2.5 and when it return a value o :price for editing it just brings one decimal, eg. 600.0, i need that i bring 2 decimals (eg. 600.00) in database is recorded 600.00, in my locales i already set for 2 decimals, and still dont work.
I tried
number_to_currency(:price, :precision => 2)
but it works well for a view like "show", i need that it return the propper value for editing, on textfield.
in my migration the field "price" is set do decimal(15,2).
Can someone help?
Thank You!
The text fields are operating on the "native" value of the field, as it is handled by ActiveRecord, not as it is stored in the database.
Currency fields are tricky since ActiveRecord is translating between the database representation and the ruby/rails representation, a BigDecimal.
If your goal is that you want to show your users $1,000.00 and enable them to edit it, some ideas:
Use the Money gem Ylan S refers to.
Use an Edit in place widget Eg screencast. You'd use number_to_currency to display the value. When clicked, the input field would show the value without the currency symbol, commas for thousands separators, etc. Note that this is how Excel works: when you edit the value of a currency field, you don't enter 1,000. You enter 1000.
In my experience, instead of using decimal for storing currency, it's best to store the amounts in cents, as an integer. This will take care of multiple problems, including the one you are having now.
I have had much success in the past using the Money gem and its companion money-rails.
Issue solved using 'delocalize' gem.
Old but gold! :) Thank you all!
The simplest way to have your text_field display a formatted value is to pass it explicitly, like this:
f.text_field :price, :value => number_to_currency(:price, :precision => 2)
You'll need to interpret (and possibly re-format) the value in the controller method that handles the form.
See How can I format the value shown in a Rails edit field?

Ruby on Rails: How to create a class schedule calendar with hour by hour breakdown?

I'm a new ruby on rails coder who is trying to create a neatly displayed calendar of the week for students to check their timetables.
I have stored the lessons in a table with the following data:
:course_id, :state_unit_code, :day_of_week, :start_date, :end_date, :start_time, :end_time, :classroom_id, :campus_id, :lecturer_id
I wish to take the data from that table and transform it into an html table similar to that shown:
I've mocked it up using table, tr td rowspan colspan and so on.
If you can point me in the right direction I'd be most appreciable.
Follows on from a post by another user (allesklar): How would you build this daily class schedule?
I would recommend using a gem for this unless you are a strong confident rails programmer with some decent experience. It's a good project if you're just doing it to learn but not so much if you actually want it to be used as a 'production app. in the real world.
I think that https://github.com/elevation/event_calendar might meet your needs. Take a look and see.
You may also need to use a separate gui date picker at some point and their are many solutions for that such as http://code.google.com/p/calendardateselect/ though this is just about picking dates, not the full calendar display of event also. But it could be handy. You'll also see 30 (!) different date pickers here: http://www.1stwebdesigner.com/freebies/jquery-calendar-plugins/ that also include ones that let you span dates.

How to convert a text date to a scoped Date in Rails?

Apologies if the title is not clear, I' not really sure how to explain this clearly.
In a Rails app I'm pulling in users' data from a 3rd party provider's API. One of the attributes is the user's birthday.
I am storing the hashed data in my database and, in certain circumstances, need to display the user's birthday in the view.
The problem is that the birthday is not formatted as a Date. Within the hash, it is in the format mm/dd/yyyy. This means that my usual date scoped formats don't work on it.
Given that I am extracting the birthday from the hashed data column as follows
<%= #user.hashed_data["info"]["birthday"] %>
what is the best/ most efficient way to handle this so that I can display localized date formats?
Do I need to split on the / symbols, and then recombine the resulting string to a date? Or am I overcomplicating this?
Thanks for any suggestions.
Try:
Date.strptime('01/31/2011', '%m/%d/%Y')
# => #<Date: 2011-01-31 (4911185/2,0,2299161)>
The simplest way to convert plain text to date or datetime is to use the chronic gem.
A very usefull parameter that you can pass to the chronic parser is the :endian_precedence . See my answer here for more details.
Regards, Dorian

Rails I18n.l wants a yaml file for every time zone...but why?

I just added a field time_zone to my user model and filled it with UTC + 01:00 and, on a second try, with 'Bern' just to test things.
Before I set this time zone thing, calls in a view like l #date, :format => :short were no problem because it took the format from my {locale}.yml file. But now, after adding time_zone, rails is looking for a {time_zone}.yml file for date conversion formats.
I don't see the real sense behind this. I know that different countries display dates and times in a different way than others. But is creating a file for each time zone the right solution, especially when a lot of time zones will have the same display format? I don't think this is DRY.
However, I need to work with time zones because dates are wrong displayed. How can I keep the behaviour of working with {locale}.yml files and... just define a time zone which converts dates displayed to the right value?
One possible solution would be creating the {time_zone}.yml files as links to the {locale}.yml files, so you only have to maintain one file instead of two (I'm assuming that the fields needed for {time_zone}.yml are present in {locale}.yml)

Resources