1

私は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'

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

前もって感謝します。

4

2 に答える 2

1

@Rob がコメントで述べたように、デフォルト値を設定するにはさまざまな方法があります。

@Dave がコメントで言及したコールバックも問題ありません。

このアプローチが機能しない主な理由は、as inではなくas inafter_initializeを明示的に使用する必要があるためだと思います。Ruby は、内部的に実装されているActiveRecord の属性に値を代入するのではなく、名前付きのローカル変数を定義していると考えます。値を割り当てたように見えるかもしれませんが、これが理由です。selfself.birth =birth =birthbirthmethod_missing@pet.birthnil

また、データベースからオブジェクトをロードしてインスタンス化すると、永続化されたオブジェクトに対しても after_initialize コールバックが呼び出されることに注意してください。initializeまた、新しいレコードに対して属性が割り当てられた後にも呼び出されます。したがって、ユーザー指定の値がデフォルトで (永続化されたレコードと新しいレコードの両方で) 踏みにじられるのを防ぐには、必ず次のようにしてください。

self.birth = value if birth.nil?

の強調if birth.nil?

于 2012-05-27T04:20:43.823 に答える
0

さて、ここに解決策があります。まず、after_initialize メソッドが実行されていません。しかし、この変更の後、それは機能しました:

class Pet < ActiveRecord::Base
  belongs_to :user
  belongs_to :petRace
  attr_accessible :birth, :exactAge, :nick
  after_initialize :init
  protected
    def init
      self.birth = DateTime.now.in_time_zone.midnight
    end
end
于 2012-05-27T04:32:54.537 に答える