Ruby - DataMapper - Form - Create New - Format of HTML to populate DateTime object in Model class

StackOverflow https://stackoverflow.com/questions/16874522

  •  30-05-2022
  •  | 
  •  

Question

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.

Was it helpful?

Solution

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, ...)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top