Take the 2-minute tour ×

Ruby hashes are great and Ruby with DataMapper is even greater... This is regarding instantiating a DateTime property in Ruby using Hashes. It is involved with DataMapper.

I have a modal, User that has a birthday that is stored as DateTime

class User
  include DataMapper::Resource

  property :id, Serial

  # Some other properties

  property :date_of_birth, DateTime

  property :gender, Enum[:male, :female, :other], {
    default: :other,

  property :children, Integer

To populate the form I use some thing like this with HTML

<form method="post">

  <input type="text" name="user[name]" id="user-name">

  <!-- other fields -->

  <select name="{what to use for year?}" id="user-birth-year>
    <option value="1980">1980</option>
    <!-- other options -->

  <select name="{what to use for month?}" id="user-birth-month>
    <!-- other options -->

  <!-- Other fields -->

In the register.rb (route) I do some thing like this...

  post '/auth/register' do
    user = User.new(params['user'])
    # Other stuff

As I understand, the has user has to kind of be similar to its fields. So how would the date_of_birth field be named to achieve this.

My assumption was to use some thing like this, but it doesn't seem to work.

:date_of_birth = {
  :year => '2010'
  :month => '11'
  :date => '20'

Which would be given by names user[data_of_birth][year] user[date_of_birth][month] and user[date_of_birth][date] for the select lists.

share|improve this question
add comment

1 Answer

up vote 1 down vote accepted

Mass assignment (doing User.new(params['user'])) isn't very good practice. Anyway, you need to obtain a DateTime or Time object somehow. You can name the fields how you want, for example:

<select name="user[date_of_birth][year]" id="user-date_of_birth-year>
  <!-- other options -->

<select name="user[date_of_birth][month]" id="user-date_of_birth-month>
  <!-- other options -->

<select name="user[date_of_birth][day]" id="user-date_of_birth-day>
  <!-- other options -->

and in your controller:

dob = DateTime.new(
User.new(:name => params['user']['name'], :date_of_birth => dob, ...)
share|improve this answer
Thanks for the info,I am curious to know why it may be bad. Is it like the user will post data that is not in the form manipulate the system other than the desired behavior (dumb ex: like get premium account without paying) It should work, I will test and accept it by tomorrow morning. –  Ziyan Junaideen Jun 1 '13 at 19:58
That is exactly the reason. Good luck with your project! –  p11y Jun 1 '13 at 20:03
add comment

Your Answer


