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 在他的评论中提到的回调也是一个不错的主意。

after_initialize我怀疑该方法对您不起作用的主要原因是您需要明确使用selfas inself.birth =而不是birth =. Ruby 认为您正在定义一个名为的局部变量,而不是为通过内部实现birth的 ActiveRecord 的属性分配一个值。这就是为什么即使您似乎为它分配了一个值。birthmethod_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 回答