私は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'
出生値が実際の日時で設定されていることは私の理解です(初期化メソッドで)。私は間違っているか、何か不足していますか? レコードを編集するとき、問題はありません。
前もって感謝します。