0

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
end

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>

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

  <!-- Other fields -->
</form>

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

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

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.

Ziyan Junaideen
  • 3,270
  • 7
  • 46
  • 71

1 Answers1

1

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>
  <option value="1980">1980</option>
  <!-- other options -->
</select>

<select name="user[date_of_birth][month]" id="user-date_of_birth-month>
  <option value="1">January</option>
  <!-- other options -->
</select>

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

and in your controller:

dob = DateTime.new(
  params['user'][date_of_birth][year].to_i,
  params['user'][date_of_birth][month].to_i,
  params['user'][date_of_birth][day].to_i
)
User.new(:name => params['user']['name'], :date_of_birth => dob, ...)
Patrick Oscity
  • 53,604
  • 17
  • 144
  • 168
  • 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 01 '13 at 19:58
  • 1
    That is exactly the reason. Good luck with your project! – Patrick Oscity Jun 01 '13 at 20:03