我从 ruby on rails 开始。我有一个简单的脚手架。
这是我的模型:
class Pet < ActiveRecord::Base
belongs_to :user
belongs_to :petRace
attr_accessible :birth, :exactAge, :nick
def initialize
birth = DateTime.now.in_time_zone.midnight
end
end
html代码
<%= form_for @pet, :html => { :class => 'form-horizontal' } do |f| %>
<div class="control-group">
<%= f.label :nick, :class => 'control-label' %>
<div class="controls">
<%= f.text_field :nick, :class => 'text_field' %>
</div>
</div>
<div class="control-group">
<%= f.label :birth, :class => 'control-label' %>
<div class="controls">
<div class="input-append date datepicker" data-date="<%=@pet.birth.strftime("%d/%m/%Y") %>" data-date-format="dd/mm/yyyy">
<%= f.text_field :birth, :class => 'input-append', :value => @pet.birth.strftime("%d/%m/%Y") %>
<span class="add-on"><i class="icon-th"></i></span>
</div>
</div>
<div class="form-actions">
<%= f.submit nil, :class => 'btn btn-primary' %>
<%= link_to t('.cancel', :default => t("helpers.links.cancel")),
pets_path, :class => 'btn' %>
</div>
<% end %>
控制器:
def new
@pet = Pet.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @pet }
end
end
我只是替换了 :birth 属性的原始代码,如下所示:
<%= f.text_field :birth, :class => 'input-append', :value => @pet.birth.strftime("%d/%m/%Y") %>
当我选择新选项时,出生属性似乎没有价值,我得到了这个执行
undefined method `[]' for nil:NilClass
Extracted source (around line #11):
8:
9: </script>
10: <%end%>
11: <%= form_for @pet, :html => { :class => 'form-horizontal' } do |f| %>
12: <div class="control-group">
13: <%= f.label :nick, :class => 'control-label' %>
14: <div class="controls">
app/views/pets/_form.html.erb:11:in `_app_views_pets__form_html_erb__3291519358612565784_70159905628180'
app/views/pets/new.html.erb:4:in `_app_views_pets_new_html_erb__1494749415896629355_70159907398120'
app/controllers/pets_controller.rb:28:in `new'
据我了解,出生值是用实际日期和时间设置的(在初始化方法中)。我错了还是错过了什么?当我编辑记录时,我没有问题。
提前致谢。