我以軌道上的紅寶石開始。我有一個簡單的腳手架。Ruby模型 - 初始化時的設置值
這裏是我的模型:
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="<%[email protected]("%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
我只是取代了原來的代碼:出生屬性,爲你可以看到這裏:
<%= f.text_field :birth, :class => 'input-append', :value => @pet.birth.strftime("%d/%m/%Y") %>
當我選擇選項新誕生的屬性似乎沒有價值,我得到這個execption
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'
這是我的理解是,誕生值設置與實際日期和時間(在初始化方法)。我錯了還是錯過了什麼?當我編輯記錄時,我沒有問題。
在此先感謝。
您可能不想重寫初始化,而是使用回調。 –
謝謝,但現在我得到了:未定義的方法'strftime'爲零:NilClass。代碼:def after_initialize birth = DateTime.now.in_time_zone.midnight end –
'@ pet'是一個新實例化的對象(即你在控制器中調用'@pet = Pet.new')?我認爲你在這裏的做法可能是錯誤的。如果您想要出生的「默認」值,可以通過遷移將其設置在數據庫中。否則,您可以將其設置在控制器中,或者如果當前不存在任何值,則可以將該字段的值設置爲今天的值。 –