Ruby - DataMapper - Form - Create New - 用于在Model类中填充DateTime对象的HTML格式

时间:2013-06-01 15:55:59

标签: ruby ruby-datamapper

Ruby哈希是很棒的,带有DataMapper的Ruby甚至更大......这是关于使用Hashes在Ruby中实例化DateTime属性。它与DataMapper有关。

我有一个模式User,其生日存储为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

要填充表单,我使用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>

register.rb(路线)中,我做了一些像这样的事情......

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

据我了解,用户必须与其字段类似。那么如何命名date_of_birth字段来实现这一点。

我的假设是使用这样的东西,但它似乎不起作用。

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

选择列表的名称user[data_of_birth][year] user[date_of_birth][month]user[date_of_birth][date]会给出。

1 个答案:

答案 0 :(得分:1)

批量作业(做User.new(params['user']))不是很好的做法。无论如何,您需要以某种方式获得DateTimeTime对象。您可以根据需要为字段命名,例如:

<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>

并在您的控制器中:

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, ...)