Rails突然停止拾取使用bootstrap-datpicker-rails
输入的值,至少我只注意到它带有日期输入。
这是一个binding.pry调用
16: def create
17: @batch = Batch.new(batch_params)
=> 18: binding.pry
19:
20: if @batch.save
21: redirect_to :root
22: else
23: render 'new'
24: end
25: end
[1] pry(#<BatchesController>)> params
=> {"utf8"=>"✓",
"authenticity_token"=>"/0IzN2EfU7MHWnwLeL/RREsqo3C7vtintD8rbmW4rsbmGhV9Q8crc7DerCAnN+CDZ2Sf4OhSgM1aVl8sl3DLfQ==",
"batch"=>{"name"=>"Batch3", "date"=>"02/14/2016"},
"commit"=>"Create New Batch",
"controller"=>"batches",
"action"=>"create"}
[2] pry(#<BatchesController>)> @batch
=> #<Batch:0x007f99ca8b1120 id: nil, name: "Batch3", date: nil, created_at: nil, updated_at: nil, active: nil>
如您所见,参数batch
具有有效的日期和名称值,但@batch
对象仅选取名称而不是日期。它在一小时前工作,我唯一改变的是UI的一些引导元素。
我的强大参数:
def batch_params
params.require(:batch).permit(:name, :date)
end
输入值的表单:
<div class='well'>
<%= form_for [@pig, @weight] do |f| %>
<div class='form-group'>
<%= f.label :date %>
<br>
<%= f.text_field :date, "data-provide" => 'datepicker' %>
</div>
<div class='form-group'>
<%= f.label :weight %>
<br>
<%= f.number_field :weight, step: 0.5 %>
</div>
<%= f.submit(@weight.new_record? ? "Add weight" : "Update weight", class:'btn btn-success') %>
<% end %>
</div>
答案 0 :(得分:5)
Rails无法开箱即用解析此日期格式。但您可以在模型中添加自定义setter来解决该问题:
# in app/models/batch.rb
def date=(string)
write_attribute(:date, DateTime.strptime(string, '%m/%d/%Y'))
end
答案 1 :(得分:0)
从下面的结果可以看出,
这不是解析"02/14/2016"
[3] ruby_project » Date.parse("02/14/2016")
ArgumentError: invalid date
[4] ruby_project » DateTime.parse("02/14/2016")
[4] ruby_project » DateTime.parse("02/14/2016")
ArgumentError: invalid date
from (pry):4:in `parse'
[5] ruby_project »
尝试使用有效日期并告诉我它是否有效